Building ActiveX servers in Qt

The QAxServer module is part of the ActiveQt framework. It consists of three classes:

  • QAxFactory defines a factory for the creation of COM objects.
  • QAxBindable provides an interface between the Qt widget and the COM object.
  • QAxAggregated can be subclassed to implement additional COM interfaces.

Some example implementations of ActiveX controls and COM objects are provided.

Topics:

Using the Library

To turn a standard Qt application into a COM server using the QAxServer library you must add axserver to the QT variable in your .pro file.

An out-of-process executable server is generated from a .pro file like this:

 TEMPLATE = app
 QT  += axserver

 RC_FILE  = qaxserver.rc
 ...

To build an in-process server, use a .pro file like this:

 TEMPLATE = lib
 QT += axserver
 CONFIG  += dll

 DEF_FILE = qaxserver.def
 RC_FILE  = qaxserver.rc
 ...

The files qaxserver.rc and qaxserver.def are part of the framework and can be used from their usual location (specify a path in the .pro file), or copied into the project directory. You can modify these files as long as it includes any file as the type library entry, ie. you can add version information or specify a different toolbox icon.

Using the axserver module will cause the qmake tool to add the required build steps to the build system:

  • Link the binary against qaxserver.lib instead of qtmain.lib
  • Call the idc tool to generate an IDL file for the COM server
  • Compile the IDL into a type library using the MIDL tool (part of the compiler installation)
  • Attach the resulting type library as a binary resource to the server binary (again using the idc tool)
  • Register the server. This step may require administrative privileges and can be skipped by setting the qaxserver_no_register configuration.

To skip the post-processing step, also set the qaxserver_no_postlink configuration.

Additionally you can specify a version number using the VERSION variable, e.g.

 TEMPLATE = lib
 VERSION = 2.5
 ...

The version number specified will be used as the version of the type library and of the server when registering.

Out-of-Process vs. In-Process

Whether your COM server should run as a stand-alone executable or as a shared library in the client process depends mainly on the type of COM objects you want to provide in the server.

An executable server has the advantage of being able to run as a stand-alone application, but adds considerable overhead to the communication between the COM client and the COM object. If the control has a programming error only the server process running the control will crash, and the client application will probably continue to run. Not all COM clients support executable servers.

An in-process server is usually smaller and has faster startup time. The communication between client and server is done directly through virtual function calls and does not introduce the overhead required for remote procedure calls. However, if the server crashes the client application is likely to crash as well, and not every functionality is available for in-process servers (i.e. register in the COM's running-object-table).

Both server types can use Qt either as a shared library, or statically linked into the server binary.

Typical Errors During the Post-Build Steps

For the ActiveQt specific post-processing steps to work the server has to meet some requirements:

  • All controls exposed can be created with nothing but a QApplication instance being present
  • The initial linking of the server includes a temporary type library resource
  • All dependencies required to run the server are in the system path (or in the path used by the calling environment; note that Visual Studio has its own set of environment variables listed in the Tools|Options|Directories dialog).

If those requirements are not met one ore more of the following errors are likely to occur:

The Server Executable Crashes

To generate the IDL the widgets exposed as ActiveX controls need to be instantiated (the constructor is called). At this point, nothing else but a QApplication object exists. Your widget constructor must not rely on any other objects to be created, e.g. it should check for null-pointers.

To debug your server run it with -dumpidl outputfile and check where it crashes.

Note that no functions of the control are called.

The Server Executable Is Not a Valid Win32 Application

Attaching the type library corrupted the server binary. This is a bug in Windows and happens only with release builds.

The first linking step has to link a dummy type library into the executable that can later be replaced by idc. Add a resource file with a type library to your project as demonstrated in the examples.

"Unable to locate DLL"

The build system needs to run the server executable to generate the interface definition, and to register the server. If a dynamic link library the server links against is not in the path this might fail (e.g. Visual Studio calls the server using the environment settings specified in the "Directories" option). Make sure that all DLLs and plugins required by your server are located in a directory that is listed in the path as printed in the error message box (see also The Windows Deployment Tool).

"Cannot open file ..."

The ActiveX server could not shut down properly when the last client stopped using it. It usually takes about two seconds for the application to terminate, but you might have to use the task manager to kill the process (e.g. when a client doesn't release the controls properly).

The Control Cannot be Instantiated

In this case, it may help to register the server as Administrator.

Implementing Controls

To implement a COM object with Qt, create a subclass of QObject or any existing QObject subclass. If the class is a subclass of QWidget, the COM object will be an ActiveX control.

 #include <QWidget>

 class MyActiveX : public QWidget
 {
     Q_OBJECT

The Q_OBJECT macro is required to provide the meta object information about the widget to the ActiveQt framework.

 Q_CLASSINFO("ClassID", "{1D9928BD-4453-4bdd-903D-E525ED17FDE5}")
 Q_CLASSINFO("InterfaceID", "{99F6860E-2C5A-42ec-87F2-43396F4BE389}")
 Q_CLASSINFO("EventsID", "{0A3E9F27-E4F1-45bb-9E47-63099BCCD0E3}")

Use the Q_CLASSINFO() macro to specify the COM identifiers for the COM object. ClassID and InterfaceID are required, while EventsID is only necessary when your object has signals. To generate these identifiers, use system tools like uuidgen or guidgen.

You can specify additional attributes for each of your classes; see Class Information and Tuning for details.

 Q_PROPERTY(int value READ value WRITE setValue)

Use the Q_PROPERTY() macro to declare properties for the ActiveX control.

Declare a standard constructor taking a parent object, and functions, signals and slots like for any QObject subclass.

 public:
     MyActiveX(QWidget *parent = 0)
     ...

     int value() const;

 public slots:
     void setValue(int v);
     ...

 signals:
     void valueChange(int v);
     ...

 };

The ActiveQt framework will expose properties and public slots as ActiveX properties and methods, and signals as ActiveX events, and convert between the Qt data types and the equivalent COM data types.

Data Types

The Qt data types that are supported for properties are:

Qt data typeCOM property
boolVARIANT_BOOL
QStringBSTR
intint
uintunsigned int
doubledouble
qlonglongCY
qulonglongCY
QColorOLE_COLOR
QDateDATE
QDateTimeDATE
QTimeDATE
QFontIFontDisp*
QPixmapIPictureDisp*
QVariantVARIANT
QVariantList (same as QList<QVariant>)SAFEARRAY(VARIANT)
QStringListSAFEARRAY(BSTR)
QByteArraySAFEARRAY(BYTE)
QRectUser defined type
QSizeUser defined type
QPointUser defined type

The Qt data types that are supported for parameters in signals and slots are:

Qt data typeCOM parameter
bool[in] VARIANT_BOOL
bool&[in, out] VARIANT_BOOL*
QString, const QString&[in] BSTR
QString&[in, out] BSTR*
QString&[in, out] BSTR*
int[in] int
int&[in,out] int
uint[in] unsigned int
uint&[in, out] unsigned int*
double[in] double
double&[in, out] double*
QColor, const QColor&[in] OLE_COLOR
QColor&[in, out] OLE_COLOR*
QDate, const QDate&[in] DATE
QDate&[in, out] DATE*
QDateTime, const QDateTime&[in] DATE
QDateTime&[in, out] DATE*
QFont, const QFont&[in] IFontDisp*
QFont&[in, out] IFontDisp**
QPixmap, const QPixmap&[in] IPictureDisp*
QPixmap&[in, out] IPictureDisp**
QList<QVariant>, const QList<QVariant>&[in] SAFEARRAY(VARIANT)
QList<QVariant>&[in, out] SAFEARRAY(VARIANT)*
QStringList, const QStringList&[in] SAFEARRAY(BSTR)
QStringList&[in, out] SAFEARRAY(BSTR)*
QByteArray, const QByteArray&[in] SAFEARRAY(BYTE)
QByteArray&[in, out] SAFEARRAY(BYTE)*
QObject*[in] IDispatch*
QRect& [in, out] struct QRect (user defined)
QSize&[in, out] struct QSize (user defined)
QPoint&[in, out] struct QPoint (user defined)

Also supported are exported enums and flags (see Q_ENUM() and Q_FLAG()). The in-parameter types are also supported as return values.

Properties and signals/slots that have parameters using any other data types are ignored by the ActiveQt framework.

Sub-Objects

COM objects can have multiple sub-objects that can represent a sub element of the COM object. A COM object representing a multi-document spread sheet application can for example provide one sub-object for each spread sheet.

Any QObject subclass can be used as the type for a sub object in ActiveX, as long as it is known to the QAxFactory. Then the type can be used in properties, or as the return type or parameter of a slot.

Property Notification

To make the properties bindable for the ActiveX client, use multiple inheritance from the QAxBindable class:

 #include <QAxBindable>
 #include <QWidget>

 class MyActiveX : public QWidget, public QAxBindable
 {
     Q_OBJECT

When implementing the property write functions, use the QAxBindable class's requestPropertyChange() and propertyChanged() functions to allow ActiveX clients to bind to the control properties.

Serving Controls

To make a COM server available to the COM system it must be registered in the system registry using five unique identifiers. These identifiers are provided by tools like guidgen or uuidgen. The registration information allows COM to localize the binary providing a requested ActiveX control, marshall remote procedure calls to the control and read type information about the methods and properties exposed by the control.

To create the COM object when the client asks for it the server must export an implementation of a QAxFactory. The easist way to do this is to use a set of macros:

 QAXFACTORY_BEGIN("{ad90301a-849e-4e8b-9a91-0a6dc5f6461f}",
                  "{a8f21901-7ff7-4f6a-b939-789620c03d83}")
     QAXCLASS(MyWidget)
     QAXCLASS(MyWidget2)
     QAXTYPE(MySubType)
 QAXFACTORY_END()

This will export MyWidget and MyWidget2 as COM objects that can be created by COM clients, and will register MySubType as a type that can be used in properties and parameters of MyWidget and MyWidget2.

The QAxFactory class documentation explains how to use this macro, and how to implement and use custom factories.

For out-of-process executable servers you can implement a main() function to instantiate a QApplication object and enter the event loop just like any normal Qt application. By default the application will start as a standard Qt application, but if you pass -activex on the command line it will start as an ActiveX server. Use QAxFactory::isServer() to create and run a standard application interface, or to prevent a stand-alone execution:

 #include <QApplication>
 #include <QAxFactory>

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     if (!QAxFactory::isServer()) {
         // create and show main window
     }
     return app.exec();
 }

This is however not necessary as ActiveQt provides a default implementation of a main function. The default implementation calls QAxFactory::startServer(), creates a QApplication instance and calls exec().

To build the ActiveX server executable run qmake to generate the makefile, and use your compiler's make tool as for any other Qt application. The make process will also register the controls in the system registry by calling the resulting executable with the -regserver command line option.

If the ActiveX server is an executable, the following command line options are supported:

OptionResult
-regserverRegisters the server in the system registry
-regserverperuserRegisters the server in the system registry for the current user (since 5.14)
-unregserverUnregisters the server from the system registry
-unregserverperuserUnregisters the server from the system registry for the current user (since 5.14)
-activexStarts the application as an ActiveX server
-dumpidl <file> -version x.yWrites the server's IDL to the specified file. The type library will have version x.y

In-process servers can be registered using the regsvr32 tool available on all Windows systems.

Typical Compile-Time Problems

The compiler/linker errors listed are based on those issued by the Microsoft Visual C++ 6.0 compiler.

"No overloaded function takes 2 parameters"

When the error occurs in code that uses the QAXCLASS() or QAXFACTORY_DEFAULT() macro, the widget class had no constructor that can be used by the default factory. Either add a standard widget constructor or implement a custom factory that doesn't require one.

When the error occurs in code that uses the QAXFACTORY_EXPORT() macro, the QAxFactory subclass had no appropriate constructor. Provide a public class constructor like

 MyFactory(const QUuid &, const QUuid &);

for your factory class.

"Syntax error: bad suffix on number"

The unique identifiers have not been passed as strings into the QAXFACTORY_EXPORT(), QAXFACTORY_BEGIN() or QAXFACTORY_DEFAULT() macro.

"Unresolved external symbol _ucm_instantiate"

The server does not export an implementation of a QAxFactory. Use the QAXFACTORY_EXPORT() macro in one of the project's implementation files to instantiate and export a factory, or use the QAXCLASS() or QAXFACTORY_DEFAULT() macro to use the default factory.

"_ucm_initialize already defined in ..."

The server exports more than one implementation of a QAxFactory, or exports the same implementation twice. If you use the default factory, the QAXFACTORY_BEGIN() or QAXFACTORY_DEFAULT() macro must only be used once in the project. Use a custom QAxFactory implementation and the QAXFACTORY_EXPORT() macro if the server provides multiple ActiveX controls.

Distributing QAxServer Binaries

ActiveX servers written with Qt can use Qt either as a shared library, or have Qt linked statically into the binary. Both ways will produce rather large packages (either the server binary itself becomes large, or you have to ship the Qt DLL).

Installing Stand-Alone Servers

When your ActiveX server can also run as a stand-alone application, run the server executable with the -regserver command line parameter after installing the executable on the target system. After that the controls provided by the server will be available to ActiveX clients.

Installing In-Process Servers

When your ActiveX server is part of an installation package, use the regsvr32 tool provided by Microsoft to register the controls on the target system. If this tool is not present, load the DLL into your installer process, resolve the DllRegisterServer symbol and call the function:

 HMODULE dll = LoadLibrary("myserver.dll");
 typedef HRESULT(__stdcall *DllRegisterServerProc)();
 DllRegisterServerProc DllRegisterServer =
     (DllRegisterServerProc)GetProcAddress(dll, "DllRegisterServer");

 HRESULT res = E_FAIL;
 if (DllRegisterServer)
     res = DllRegisterServer();
 if (res != S_OK)
     // error handling

Distributing Servers over the Internet

If you want to use controls in your server in web-pages you need to make the server available to the browser used to view your page, and you need to specify the location of the server package in your page.

To specify the location of a server, use the CODEBASE attribute in the OBJECT tag of your web-site. The value can point to the server file itself, to an INF file listing other files the server requires (e.g. the Qt DLL), or a compressed CAB archive.

INF and CAB files are documented in almost every book available about ActiveX and COM programming as well as in the MSDN library and various other Online resources. The examples include INF files that can be used to build CAB archives:

 [version]
     signature="$CHICAGO$"
     AdvancedINF=2.0
  [Add.Code]
     simpleax.exe=simpleax.exe
  [simpleax.exe]
     file-win32-x86=thiscab
     clsid={DF16845C-92CD-4AAB-A982-EB9840E74669}
     RegisterServer=yes

The CABARC tool from Microsoft can easily generate CAB archives:

 cabarc N simpleax.cab simpleax.exe simple.inf

The INF files assume a static build of Qt, so no dependencies to other DLLs are listed in the INF files. To distribute an ActiveX server depending on DLLs you must add the dependencies, and provide the library files with the archive.

Using the Controls

To use the ActiveX controls, e.g. to embed them in a web page, use the <object> HTML tag.

 <object ID="MyActiveX1" CLASSID="CLSID:ad90301a-849e-4e8b-9a91-0a6dc5f6461f">
    ...
 <\object>

To initialize the control's properties, use

 <object ID=...>
     <param name="name" value="value">
 <\object>

If the web browser supports scripting use JavaScript, VBScript and forms to script the control. The ActiveQt Examples include demonstration HTML pages for the example controls.

Supported and Unsupported ActiveX Clients

The following is largly based on our own experiements with ActiveX controls and client applications, and is by no means complete.

Supported Clients

These standard applications work with ActiveX controls developed with ActiveQt. Note that some clients support only in-process controls.

  • Internet Explorer
  • Microsoft ActiveX Control Test Container
  • Microsoft Visual Studio 6.0
  • Microsoft Visual Studio.NET/2003
  • Microsoft Visual Basic 6.0
  • MFC- and ATL-based containers
  • Sybase PowerBuilder
  • ActiveQt based containers

Microsoft Office applications are supported, but you need to register the controls as "Insertable" objects. Reimplement QAxFactory::registerClass to add this attribute to the COM class, or set the "Insertable" class info for your class to "yes" using the Q_CLASSINFO macro.

Unsupported Clients

We have not managed to make ActiveQt based COM objects work with the following client applications.

  • Borland C++ Builder (Versions 5 and 6)
  • Borland Delphi

Typical Runtime Errors

The Server Does Not Respond

If the system is unable to start the server (check with the task manager whether the server runs a process), make sure that no DLL the server depends on is missing from the system path (e.g. the Qt DLL!). Use a dependency walker to view all dependencies of the server binary.

If the server runs (e.g. the task manager lists a process), see the following section for information on debugging your server.

The Object Cannot Be Created

If the server could be built and registered correctly during the build process, but the object cannot be initiliazed e.g. by the OLE/COM Object Viewer application, make sure that no DLL the server depends on is missing from the system path (e.g. the Qt DLL). Use a dependency walker to view all dependencies of the server binary.

If the server runs, see the following section for information on debugging your server.

Crashes when unloading and reloading COM servers

If ActiveQt COM servers utilize Qt modules beyond those found in Qt Base, it is necessary to activate the COM server as an out-of-process COM server. Attempting to activate an in-process COM server that includes modules such as Qt Quick may result in a crash after unloading the COM server.

Crash or unexpected behavior during outgoing COM calls

Be aware that an out-of-process COM server will be processing its message queue while it is performing an outgoing call to the client. This can lead to unexpected behavior or crash if the client is at the same time calling the server. In this situation, the incoming call will be executed in the server before the outgoing call returns. In particular, if the client closes an ActiveX control while the control is calling back into the client, this can lead to crash. Such reentrancy problems can be mitigated using message filters (IMessageFilter and CoRegisterMessageFilter).

Debugging Runtime Errors

To debug an in-process server in Visual Studio, set the server project as the active project, and specify a client "executable for debug session" in the project settings (e.g. use the ActiveX Test Container). You can set breakpoints in your code, and also step into ActiveQt and Qt code if you installed the debug version.

To debug an executable server, run the application in a debugger and start with the command line parameter -activex. Then start your client and create an instance of your ActiveX control. COM will use the existing process for the next client trying to create an ActiveX control.

Class Information and Tuning

To provide attributes for each COM class, use the Q_CLASSINFO macro, which is part of Qt's meta object system.

KeyMeaning of value
VersionThe version of the class (1.0 is default)
DescriptionA string describing the class.
ClassIDThe class ID. You must reimplement QAxFactory::classID if not specified.
InterfaceIDThe interface ID. You must reimplement QAxFactory::interfaceID if not specified.
EventsIDThe event interface ID. No signals are exposed as COM events if not specified.
DefaultPropertyThe property specified represents the default property of this class. Ie. the default property of a push button would be "text".
DefaultSignalThe signal specified respresents the default signal of this class. Ie. the default signal of a push button would be "clicked".
LicenseKeyObject creation requires the specified license key. The key can be empty to require a licensed machine. By default classes are not licensed. Also see the following section.
StockEventsObjects expose stock events if value is "yes". See QAxFactory::hasStockEvents()
ToSuperClassObjects expose functionality of all super-classes up to and including the class name in value. See QAxFactory::exposeToSuperClass()
InsertableIf the value is "yes" the class is registered to be "Insertable" and will be listed in OLE 2 containers (ie. Microsoft Office). This attribute is not be set by default.
AggregatableIf the value is "no" the class does not support aggregation. By default aggregation is supported.
CreatableIf the value is "no" the class cannot be created by the client, and is only available through the API of another class (ie. the class is a sub-type).
RegisterObjectIf the value is "yes" objects of this class are registered with OLE and accessible from the running object table (ie. clients can connect to an already running instance of this class). This attribute is only supported in out-of-process servers.
MIMEThe object can handle data and files of the format specified in the value. The value has the format mime:extension:description. Multiple formats are separated by a semicolon.
CoClassAliasThe classname used in the generated IDL and in the registry. This is esp. useful for C++ classes that live in a namespace - by default, ActiveQt just removes the "::" to make the IDL compile.
Implemented CategoriesList of comma-separated Category ID (CATID) UUIDs. Generic mechanism for specifying additional container capabilities, in addition to "control", "insertable" etc. Typical CATIDs include CATID_InternetAware ("{0DE86A58-2BAA-11CF-A229-00AA003D7352}"), CATID_SafeForScripting ("{7DD95801-9882-11CF-9FA9-00AA006C42C4}") as well as user-defined CATID values.

Note that both keys and values are case sensitive.

The following declares version 2.0 of a class that exposes only its own API, and is available in the "Insert Objects" dialog of Microsoft Office applications.

 class MyActiveX : public QWidget
 {
     Q_OBJECT
     Q_CLASSINFO("Version", "2.0")
     Q_CLASSINFO("ClassID", "{7a4cffd8-cbcd-4ae9-ae7e-343e1e5710df}")
     Q_CLASSINFO("InterfaceID", "{6fb035bf-8019-48d8-be51-ef05427d8994}")
     Q_CLASSINFO("EventsID", "{c42fffdf-6557-47c9-817a-2da2228bc29c}")
     Q_CLASSINFO("Insertable", "yes")
     Q_CLASSINFO("ToSuperClass", "MyActiveX")
     Q_PROPERTY(...)

 public:
     MyActiveX(QWidget *parent = 0);

     ...
 };

Developing Licensed Components

If you develop components you might want to control who is able to instantiate those components. Since the server binary can be shipped to and registered on any client machine it is possible for anybody to use those components in his own software.

Licensing components can be done using a variety of techniques, e.g. the code creating the control can provide a license key, or the machine on which the control is supposed to run needs to be licensed.

To mark a Qt class as licensed specify a "LicenseKey" using the Q_CLASSINFO() macro.

 class MyLicensedControl : public QWidget
 {
     Q_OBJECT
     Q_CLASSINFO("LicenseKey", "<key string>")
     ...
 };

The key is required to be able to create an instance of MyLicensedControl on a machine that is not licensed itself. The licensed developer can now redistributes the server binary with his application, which creates the control using the value of "LicenseKey", while users of the application cannot create the control without the license key.

If a single license key for the control is not sufficient (ie. you want differnet developers to receive different license keys) you can specify an empty key to indicate that the control requires a license, and reimplement QAxFactory::validateLicenseKey() to verify that a license exists on the system (ie. through a license file).

More Interfaces

ActiveX controls provided by ActiveQt servers support a minimal set of COM interfaces to implement the OLE specifications. When the ActiveX class inherits from the QAxBindable class it can also implement additional COM interfaces.

Create a new subclass of QAxAggregated and use multiple inheritance to subclass additional COM interface classes.

 class AxImpl : public QAxAggregated, public ISomeCOMInterface
 {
 public:
     AxImpl() {}

     long queryInterface(const QUuid &iid, void **iface);

     // IUnknown
     QAXAGG_IUNKNOWN

     // ISomeCOMInterface
     ...
 }

Reimplement the QAxAggregated::queryInterface() function to support the additional COM interfaces.

 long AxImpl::queryInterface(const QUuid &iid, void **iface)
 {
     *iface = 0;
     if (iid == IID_ISomeCOMInterface)
         *iface = (ISomeCOMInterface *)this;
     else
         return E_NOINTERFACE;

     AddRef();
     return S_OK;
 }

Since ISomeCOMInterface is a subclass of IUnknown you will have to implement the QueryInterface(), AddRef(), and Release() functions. Use the QAXAGG_IUNKNOWN macro in your class definition to do that. If you implement the IUnknown functions manually, delegate the calls to the interface pointer returned by the QAxAggregated::controllingUnknown() function, e.g.

 HRESULT AxImpl::QueryInterface(REFIID iid, void **iface)
 {
     return controllingUnknown()->QueryInterface(iid, iface);
 }

Do not support the IUnknown interface itself in your queryInterface() implementation.

Implement the methods of the COM interfaces, and use QAxAggregated::object() if you need to make calls to the QObject subclass implementing the control.

In your QAxBindable subclass, implement QAxBindable::createAggregate() to return a new object of the QAxAggregated subclass.

 class MyActiveX : public QWidget, public QAxBindable
 {
     Q_OBJECT

 public:
     MyActiveX(QWidget *parent);

     QAxAggregated *createAggregate()
     {
         return new AxImpl();
     }
 };

See also ActiveQt Framework.