.Net COM Interop

The ultimate goal of COM Interop is to provide access to the existing COM components without requiring that the original component be modified. This tries to make the .NET types equivalent to the COM Types.

COM Interop and Marshalling:

COM had a mechanism of marshalling and un-marshalling to convert between the source and target data types. This is now totally covered in COM Interop using RCW or Runtime Callable Wrapper. This automatically converts the .Net data types to the corresponding COM data types.

RegAsm and tlbimp in COM Interop

In addition, COM Interop allows COM developers to access managed objects as easily as they access other COM objects. It provides a specialized utility (RegAsm.exe) that exports the managed types into a type library and registers the managed component as a traditional COM component. At run time, the common language runtime marshals data between COM objects and managed objects as needed.

This tutorial shows how C# can use COM objects to develop applications. First thing to be done is the creation of wrapper class for the selected COM object. It can be done manually through the command line application called TlbImp.exe (Type Library Importer). This utility converts COM type library to the .NET Framework metadata. This procedure can be done automatically through the .NET environment. We just need to add reference to the COM object to our C# project. So, type in .NET command line next string: tlbimp $WindowsPath$system32quartz.dll /out: quartzNET.dll. This command will create a new dll with types that are compatible with any of Managed .NET languages. Now we can add this dll to our C# project or compile our C# file with additional feature “/r quartzNET.dll”.

The following is an example of usage this COM object in C# managed code:

quartzNET.FilgraphManager manager = new quartzNET.FilgraphManagerClass();
quartzNET.IMediaControl mc = (quartzNET.IMediaControl)manager;
mc.RenderFile(args[0]);
mc.Run();
// Wait for completion.
Console.WriteLine(“Press Enter to continue.”);
Console.ReadLine();

Here is the MediaControl object, which was created in COM. This application gets a name of video file that we want to play from command line and shows it. So, this is a simple example of usage COM Interop. To compile an attached example we just need this quartzNET.dll (is attached too) and .NET command line. Type here next command csc InteropSample.cs /r:quartzNET.dll. It must create an executable file, but it can be run using command line, just type InteroPsample.exe some.avi. So, it opens a console application and also runs a standard Windows media player control to play the video.

Click here to download the C# Com Interop Sample code.