Tuesday, November 28, 2006

C++ Calling .Net

C++ & .Net

Calling COM objects from .Net is very trivial using the interop.x assemblies or by creating the wrapper classes mannualy using the tlbimp.exe utility supplied by M$.

But, what about the opposite direction – it doesn’t look that simple at all…

Well, Appararently it is.

First Step: .Net Side

First thing, in order for a .Net class to be exposed to unmanaged code, there are some steps needed.
First, we need to assinge our project with a strong file.
Add the following line to the AssemblyInfo.cs file:
(in VS.Net 2K5, you can do this in the properties page)



[assembly: AssemblyKeyFileName(@"C:\Sternr.snk")]


Next, we need to tell the VS.Net to register it as a COM object, using the "Register For Com Interop" checkbox in the Project Settings.

Ok, now we need to create (if you don’t already have!) an interface for each class we want to expose.
Both the interface and your class should have the following attribute:


[System.Runtime.InteropServices.Guid("YOUR-GUID")]


Notice: Each one of them should have a DIFFERENT GUID

The C++ (unmanaged) Side
Add the following to your code:
(remmember to change from IDotNetClass to your interface name)


IDotNetClass *dotNetInstance=NULL;

/* Initialize the COM Server */
CoInitialize(NULL);

HRESULT hr;
/* Create the instance of the .Net object */
hr = coCreateInstance(CLSID_DotNetClass,
    NULL,CLSCTX_LOCAL_SERVER,
    IID_IDotNetClass,reinterpret_cast(&dotNetInstance));

if (FAILED(hr))
{
//TODO: Add error logging
return;
}

/* And that's it - call your .Net methods like any COM object */
dotNetInstance->MyFunc(myParameters);

/* Finalization code */
dotnetInstance->Release();
CoUninitialize();


And that's it!
Aint so hard isnt it?
For further info, or the source code of an example project, mail me

No comments: