10

I am wondering what's the way to call a c# class method from C++(Native, not C++ CLI) code? Need simple and elegant way

user496949
  • 83,087
  • 147
  • 309
  • 426

4 Answers4

11

You can embed any CLR assembly (C#, VB.NET, F#, ...) in a native C++ program using what's called "CLR Hosting". This is how native programs (such as SQL Server) support .NET code extensions. E.g. SQL CLR in SQL Server.

You load the CLR into a native process using CorBindToRuntimeEx() for .NET 2.0 and CLRCreateInstance() in .NET 4.

Details can be found on MSDN, or Jeff Richter's book CLR via C#.

Alex Budovski
  • 17,947
  • 6
  • 53
  • 58
9

Turn your C# assembly into a COM visible one and use COM interfaces. That is the only way to make it work beside self made IPC as far as I know. The problem comes from the .NET environment under which the .NET assembly must run and C++ runs under its native C++ environment.

The only way of communicating is either an IPC mechanism (sockets, ...) or use COM, as the processes have to be "decoupled".

Here is a tutorial for the COM based solution:

Justin
  • 84,773
  • 49
  • 224
  • 367
jdehaan
  • 19,700
  • 6
  • 57
  • 97
  • 2
    According to Sasha there are 2 more ways actually. – gideon Nov 26 '10 at 06:38
  • 1
    Yup, there's no requirement for the "decoupling" suggested. The ".Net" environment is basically mscoree.dll, and it can load in native processes. – MSalters Nov 26 '10 at 08:11
9

Sasha Goldshtein is the man for this stuff:

There are again several ways to do it: 1. Reverse P/Invoke (has to start from .NET delegate passed as callback, so this is only good if the "action" begins in your .NET code); 2. COM interop (every .NET class can also be a COM object, with or without explicit interfaces); 3. C++/CLI wrapper classes.

See http://blogs.microsoft.co.il/blogs/sasha/archive/2008/02/16/net-to-c-bridge.aspx

See also :
http://www.gregcons.com/KateBlog/CallingManagedCodeFromNativeCode.aspx

gideon
  • 19,329
  • 11
  • 72
  • 113
0

the simplest way is to use C++/CLI. If you can't use that in your code, write a wrapper dll and call that dll.

Tobias Langner
  • 10,634
  • 6
  • 46
  • 76