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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With