views:

1671

answers:

4

Hi,

Is there a way to create C# objects and call methods from unmanaged C++, but without using COM Iterop? I am looking for something like JNI (but for .Net), where you can manually create the VM, create objects, etc.

A: 

You can decide file-by-file in your C++ project whether or not to use managed C++. Try changing the settings a file in your project so that it compiles as managed. Put the calls there to your C# object.

There's a cost to crossing the C++/C# border, so you should analyse where to do it. Like, you wouldn't want to do it inside a loop.

Corey Trager
+4  A: 

If you are using C++/CLI then you can interact directly with both the managed world and unmanaged code, so interop is trivial.

You can also host the CLR yourself, and whilst the hosting API is COM based, you can then create any managed object. The process isn't a difficult as it sounds as a few API calls encapsulate a lot of functionality. There is a lot of info online, for example the MSDN documentation on "Hosting the Common Language Runtime".

Rob Walker
+2  A: 

There is a somewhat "undocumented" way of exporting C style API from a .NET class / method.

This ultimately leads to a situation where a .NET dll has exported APIs that can be called from C/C++ or anything that can consume .DLLs for that matter.

If you are into "reading" (beh ;) you can get a book called: Inside Microsoft® .NET IL Assembler where you'll find this technique in chapter 15: "Managed Methods as Unmanaged Exports"

There's also a nice example project on code-project you can use as a starting point for 32-bit environments: http://www.codeproject.com/KB/dotnet/DllExport.aspx

damageboy
A: 

I am author of jni4net, open source intraprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you.

Pavel Savara