Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can create a managed C++ interop DLL to act as a wrapper around the C# library. </p> <p>Most tutorials on managed C++ unfortunately only explain how to wrap unmanaged C++ for use in C#. But it can work the other way also.</p> <p>Define an abstract interface class in your native C++ code, then create a concrete subclass inside the managed C++ DLL. Call into your C# objects in the method implementations.</p> <p>Finally, export a factory function that will instantiate the implementation class and return a base-class pointer that your native code can use.</p> <p>Here's a quick example:</p> <p>First, define the class interface in your native DLL.</p> <p><strong>interopclassbase.h</strong></p> <pre><code>class InteropClassBase { public: virtual void doStuff() = 0; virtual int getValue() = 0; virtual void getString(CString* outStr) = 0; }; </code></pre> <p>Now you need to create a C++/CLI DLL that will allow you to mix native and managed code in a single assembly. Add a new C++ project to your solution, and in the project configuration set the <a href="http://msdn.microsoft.com/en-us/library/k8d11d4s(VS.80).aspx" rel="nofollow noreferrer">"Common Language Runtime Support"</a> option to <strong>Mixed</strong> (/clr). </p> <p>Once you've added a reference to your C# library (which we'll call ManagedLibrary) we can implement the interop class:</p> <p><strong>interopclass.cpp</strong></p> <pre><code>#include "interopclassbase.h" #include &lt;vcclr.h&gt; public class InteropClass : public InteropClassBase { protected: gcroot&lt;ManagedLibrary::ManagedObject^&gt; m_managedObject; public: InteropClass() { m_managedObject = gcnew ManagedLibrary::ManagedObject(); } virtual void doStuff() { m_managedObject-&gt;doStuff(); } virtual int getValue() { return m_managedObject-&gt;getValue(); } virtual void getString(CString* pOutStr) { System::String^ managedString = m_managedObject-&gt;getString(); CString nativeString(managedString); // overloaded CString constructor if (pOutStr) *pOutStr = nativeString; } }; __declspec(dllexport) InteropClassBase* getImplementationPointer() { return new InteropClass(); } </code></pre> <p>Now you just need to load the interop DLL from your native project and call the exported function.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload