Click here to Skip to main content
15,891,253 members
Articles / Programming Languages / C

COM in plain C, Part 2

Rate me:
Please Sign up or sign in to vote.
4.96/5 (98 votes)
20 Apr 2006CPOL39 min read 275.8K   6.2K   165  
How to write a COM component in C that can be used by script languages such as VBscript, Visual BASIC, jscript, etc.
// This is a C example that tests the IExample COM component (in IExample.dll).

#include <windows.h>
#include <objbase.h>
#include <stdio.h>
#include "../IExample/IExample.h"

int main(int argc, char **argv)
{
	IExample		*exampleObj;
	IClassFactory	*classFactory;
	HRESULT			hr;

	// We must initialize OLE before we do anything with COM objects. NOTE:
	// some COM components, such as the IE browser engine, require that you
	// use OleInitialize() instead. But our COM component doesn't require this
	if (!CoInitialize(0))
	{
		// Get IExample.DLL's IClassFactory
		if ((hr = CoGetClassObject(&CLSID_IExample, CLSCTX_INPROC_SERVER, 0, &IID_IClassFactory, &classFactory)))
			MessageBox(0, "Can't get IClassFactory", "CoGetClassObject error", MB_OK|MB_ICONEXCLAMATION);
		else
		{
			// Create an IExample object
			if ((hr = classFactory->lpVtbl->CreateInstance(classFactory, 0, &IID_IExample, &exampleObj)))
			{
				classFactory->lpVtbl->Release(classFactory);
				MessageBox(0, "Can't create IExample object", "CreateInstance error", MB_OK|MB_ICONEXCLAMATION);
			}
			else
			{
				char	buffer[80];

				// Release the IClassFactory. We don't need it now that we have the one
				// IExample we want
				classFactory->lpVtbl->Release(classFactory);

				// Call SetString to set the text "Hello world!"
				exampleObj->lpVtbl->SetString(exampleObj, "Hello world!");

				// Retrieve the string to make sure we get "Hello world!"
				exampleObj->lpVtbl->GetString(exampleObj, buffer, sizeof(buffer));

				printf("string = %s (should be Hello World!)\n", buffer);

				// Release the IExample now that we're done with it
				exampleObj->lpVtbl->Release(exampleObj);
			}
		}

		// When finally done with OLE, free it
		CoUninitialize();
	}
	else
		MessageBox(0, "Can't initialize COM", "CoInitialize error", MB_OK|MB_ICONEXCLAMATION);

	return(0);
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions