I have an native C++ dll, some header files and the import library. Is there a way how to instantiate an object within C# that is defined in the dll?
The two ways I’m aware of are:
- to wrap the C++ code into COM
- to use DLLImport and external C functions
C++/CLI is your friend for this. You’ll run into one problem though: it is not possible to store standard C++ objects inside C++/CLI ref or value classes (the ones for .NET). So you’ll have to resort to the following class (that you can modify) that I use in production code:
Usage:
Handle<MyCppClass>^ handle;inside a C++/CLI class. You then implement stub methods, forwarding them to thehandlemember. Garbage collected objects will call destructors of the C++ class instance iff there is no more pointer to it: