Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling managed c# functions from unmanaged c++

How to call managed c# functions from unmanaged c++

like image 814
user186246 Avatar asked Apr 27 '10 09:04

user186246


People also ask

How is unmanaged code executed?

Execution of Unmanaged Code In C# the unmanaged code is directly executed by the operating system. Generally, the executable files of unmanaged or unsafe code are in the form of binary images which are loaded into the memory.

What is managed C++ code?

Managed C++ is a language invented by Microsoft, that compiles to bytecode run by the . NET Framework. It uses mostly the same syntax as C++ (hence the name) but is compiled in the same way as C# or VB.NET; basically only the syntax changes, e.g. using '->' to point to a member of an object (instead of '.

How do I call C++ code from C#?

If you want to use C++ in c# code directly, you can create a CLR(C++/CLI) project, then you can write c++ and c# code in the same project.


2 Answers

Or use a project of mine that allows C# to create unmanaged exports. Those can be consumed as if they were written in a native language.

like image 146
Robert Giesecke Avatar answered Oct 21 '22 23:10

Robert Giesecke


I used COM interop first, but by now I switched to IJW (it just works), as it is a lot simpler. I have a wrapper C++/CLR DLL (compile with /clr).

A simple example (using statics to make the calls easier):

namespace MyClasses       
{
    public class MyClass
    {
        public static void DoSomething()
        {
            MessageBox.Show("Hello World");
        }
    }
}

In the DLL I can reference namespaces as follows:

using namespace MyClasses;

And call it:

__declspec(dllexport) void CallManagedCode()
{
    MyClass::DoSomething();
}

Now you have an unmanaged DLL export "CallManagedCode" which calls into the managed code.

Of course, you also have to convert data between the managed/unmanaged boundary. Starting with VS2008, Microsoft includes a marshal-helper for converting between unmanaged and managed types. See http://msdn.microsoft.com/en-us/library/bb384865.aspx

like image 43
Daniel Rose Avatar answered Oct 21 '22 22:10

Daniel Rose