You can create a managed DLL for interacting with C ++ to act as a wrapper around the C # library.
Most guided C ++ manuals, unfortunately, only explain how to wrap unmanaged C ++ for use in C #. But it can work in another way.
Define the abstract interface class in your own C ++ code, then create a specific subclass inside the managed C ++ DLL. Call your C # objects in the method implementation.
Finally, export the factory function, which will instantiate the implementation class and return a pointer to the base class that your own code can use.
Here is an example:
First, define the class interface in your native DLL.
interopclassbase.h
class InteropClassBase { public: virtual void doStuff() = 0; virtual int getValue() = 0; virtual void getString(CString* outStr) = 0; };
Now you need to create a C ++ / CLI DLL that will allow you to mix your own and managed code in one assembly. Add a new C ++ project, and in the project configuration, set "Common Language Runtime Support" for the Mixed (/ clr) parameter.
Once you have added a link to your C # library (which we will call ManagedLibrary), we can implement the interop class:
interopclass.cpp
#include "interopclassbase.h" #include <vcclr.h> public class InteropClass : public InteropClassBase { protected: gcroot<ManagedLibrary::ManagedObject^> m_managedObject; public: InteropClass() { m_managedObject = gcnew ManagedLibrary::ManagedObject(); } virtual void doStuff() { m_managedObject->doStuff(); } virtual int getValue() { return m_managedObject->getValue(); } virtual void getString(CString* pOutStr) { System::String^ managedString = m_managedObject->getString(); CString nativeString(managedString); // overloaded CString constructor if (pOutStr) *pOutStr = nativeString; } }; __declspec(dllexport) InteropClassBase* getImplementationPointer() { return new InteropClass(); }
Now you just need to load the DLL interaction from your own project and call the exported function.
source share