views:

3750

answers:

4

Hi,

I want to call my .NET code from unmanaged C++. My process entrypoint is .NET based, so I don't have to worry about hosting the CLR. I know it can be done using COM wrappers for .NET objects, but I would like to access individual static methods of managed classes, so COM isn't my shortest/easiest route.

Thanks!

+1  A: 

Assuming you are talking about real unmanaged code - not just native C++ running in a mixed-mode assembly compiled with /clr - the easiest way is to create a wrapper to your .NET code in C++/CLI. You can then export the C++/CLI methods by just marking them with __declspec(dllexport).

Alternatively, if you have control over the invocation of the unmanaged code, you can marshal function-pointers to your .NET methods and pass them to the unmanaged code.

Rasmus Faber
+1  A: 

Take a look at the GCHandle class and the gcroot keyword, which provides a typesafe, templated wrapper around GCHandle.

You can use these to hold a reference to a CLR object (or a boxed value) in native code.

MSDN has a basic tutorial here.

Stu Mackellar
Note that this requires /clr to be enabled.
Rasmus Faber
A: 

Your calling code is C++ with /clr enabled. Right?

If yes, then you can simply use the using statement to use your .NET dll in your code. Something like:

#using <Mydll.dll>

and then you can simply make the objects of your managed classes like:

MyNameSpace::MyClass^ obj = new MyNameSpace::MyClass();

If you want to make this obj a data member of your class the using gcroot is the way to go.

Aamir
useful, but he did say "from unmanaged C++". /clr stops it being unmanaged.
gbjbaanb
I think this is what he specifically mentioned.<i>My process entrypoint is .NET based, so I don't have to worry about hosting the CLR</i>
Aamir
He might also have meant that he is P/Invoking into a completely unmanaged C++ dll and want to call back into the CLR again.
Rasmus Faber
+1  A: 

I believe you are looking for Reverse PInvoke. If you google for reverse pinvoke you'll get a lot of helpful entries. I think the following has a good quick and dirty example.

link text

JaredPar