Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal a C++ class to C#

Tags:

c++

c#

.net

interop

I need to access code in a native C++ DLL in some C# code but am having issues figuring out the marshaling. I've done this before with code that was straight C, but seem to have found that it's not directly possible with C++ classes. Made even more complicated by the fact that many of the classes contain virtual or inline functions. I even tried passing the headers through the PInvoke Interop Assistant, but it would choke on just about everything and not really no what to do... I'm guessing because it's not really supported.

So how, if at all possible, can you use a native C++ class DLL from .NET code. If I have to use some intermediary (CLR C++?) that's fine.

like image 733
Adam Haile Avatar asked Apr 21 '10 17:04

Adam Haile


People also ask

What is Marshal class in C#?

Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks, and converting managed to unmanaged types, as well as other miscellaneous methods used when interacting with unmanaged code.

What is marshalling in C++?

Marshaling requires a context only when you marshal from managed to native data types and the native type you are converting to does not have a destructor for automatic clean up. The marshaling context destroys the allocated native data type in its destructor.

What is IntPtr C#?

The IntPtr type can be used by languages that support pointers and as a common means of referring to data between languages that do and do not support pointers. IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System. IO.


1 Answers

There is really no easy way to do this in C# - I'd recommend making a simple wrapper layer in C++/CLI that exposes the C++ classes as .NET classes.

It is possible to use P/Invoke and lots of cleverness to call C++ virtual methods, but I wouldn't go this route unless you really had no other choice.

like image 140
Steve Dennis Avatar answered Oct 20 '22 00:10

Steve Dennis