Friday, September 19, 2008

Exposing .NET Components to COM

Looking on MSDN website you'll find this:
http://msdn.microsoft.com/en-us/library/zsfww439.aspx
So as you can see, you can't expose static components to COM.

C# code:
namespace ClassLibrary1{
[Guid("4322F88E95-DD27-4ae6-B6DE-054440FC70AA")]
[InterfaceType (ComInterfaceType.InterfaceIsIDispatch)]
[ComVisible(true)]
public interface _Class1
{
[DispId(1)]
int Add(int i);
}

[Guid("13FE123D-4D34-495F-AB4D-909BBB463EEA")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("ClassLibrary1.Class1")]
[ComVisible(true)]
[ComDefaultInterfaceAttribute(typeof(_Class1))]
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;
CoInitialize(NULL);
ClassLibrary1::_Class1Ptr p(__uuidof(ClassLibrary1::Class1));
com_ptr = p;
long a = com_ptr->Add(1);
CoUninitialize();
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: