Introduction
Component Object Model is a method to facilitate communication between different applications and languages. There are many other ways to structure software components. What makes COM interesting is that it is a widely accepted interoperability standard. In addition, the standard explains the way the memory should be organized for all the objects.
Interfaces are the contract between the client and the server, i.e. an interface is the way in which an object exposes its functionality to the outside world. In COM, an interface is a table of pointers to functions implemented by the object. The table represents the interface, and the functions to which it points are the methods of that interface.
Creating COM components in .NET
Creating COM components in .NET is not that difficult as in C++. The following steps explain the way to create the COM server in C#:
- Create a new Class Library project.
- Create a new interface, say
IManagedInterface
, and declare the methods required. Then provide the Guid
(this is the IID
) for the interface using the GuidAttribute
defined in System.Runtime.InteropServices
. The Guid
can be created using the Guidgen.exe. [Guid("3B515E51-0860-48ae-B49C-05DF356CDF4B")]
- Define a class that implements this interface. Again provide the
Guid
(this is the CLSID
) for this class also.
- Mark the assembly as
ComVisible
. For this go to AssemblyInfo.cs file and add the following statement [assembly: ComVisible (true)]
. This gives the accessibility of all types within the assembly to COM.
- Build the project. This will generate an assembly in the output path. Now register the assembly using regasm.exe (a tool provided with the .NET Framework)- regasm \bin\debug\ComInDotNet.dll \tlb:ComInDotNet.tlb This will create a TLB file after registration.
- Alternatively this can be done in the Project properties -> Build -> check the Register for COM interop.
The COM server is ready. Now a client has to be created. It can be in any language. If the client is .NET, just add the above created COM assembly as reference and use it.
The following steps explain the method to create an unmanaged client. Here the client is in VC++ 6.0.
- Create an MFC AppWizard EXE using the wizard in MSDEV 6.0.
- Import the COM server (TLB file generated by regasm.exe) using the
#import
directive. #import �ComInDotNet.tlb� no_namespace named_guids raw_interfaces_only
.
- Now the COM library should be loaded using the
CoInitialize
and component can be created using CoCreateInstance
.
- Next the methods defined in the COM Server can be invoked.
pInterface->Execute(�blah blah blah�);