Microsoft DirectX 9.0

Using C to Access COM Objects

Although C++ is the most commonly used language for Component Object Model (COM) programming, you can also access COM objects using C. Doing so is relatively straightforward, but requires a somewhat more complex syntax.

Every COM object has a vtable that contains a list of pointers to the methods that the object exposes. An interface pointer points to the appropriate location in the vtable, which in turn contains a pointer to the particular method you are calling. The vtable is not mentioned elsewhere in this documentation because with C++, the vtable is essentially invisible. However, if you want to call COM methods with C, you must include an additional level of indirection that explicitly references the vtable.

The following code fragment illustrates how to call the IDirectPlay8Peer::Initialize method with the C++ calling convention.

g_pDP->Initialize( NULL, DirectPlayMessageHandler, 0 );

To make the same method call from C, use the following syntax. The conventional name for the vtable pointer is lpVtbl.

g_pDP->lpVtbl->Initialize(g_pDP,NULL, DirectPlayMessageHandler, 0);

Some components have macros defined in their header files that resolve to the correct calling convention. See Using Macros to Call DirectX COM Methods for details.

© 2002 Microsoft Corporation. All rights reserved.