Friday, September 19, 2008

Exposing .NET Components to COM

Looking on MSDN website you'll find this:
So as you can see, you can't expose static components to COM.

C# code:
namespace ClassLibrary1{
[InterfaceType (ComInterfaceType.InterfaceIsIDispatch)]
public interface _Class1
int Add(int i);

public class Class1 : _Class1
public int Add(int i)
return i + 10;

C++ code:
#include "stdafx.h"
//the location must point to the tlb file
#import "D:\\ClassLibrary1\\bin\\Debug\\ClassLibrary1.tlb"
int _tmain(int argc, _TCHAR* argv[])
ClassLibrary1::_Class1 *com_ptr;
ClassLibrary1::_Class1Ptr p(__uuidof(ClassLibrary1::Class1));
com_ptr = p;
long a = com_ptr->Add(1);
return 0;

To make this work, you have to Register the .NET library to COM from Properties-Build tab and run the command : regasm ClassLibrary1 /tbl:ClassLibrary1.tlb

To deploy this, you'll have to gacutil the assembly.
gacutil /i ClassLibrary1.dll but first you'll have to strong-name sign it.

No comments: