Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a self-memory-pinning C++/CLI class?
    text
    copied!<p>I'm creating a .NET wrapper around a C++ library (I don't have access to the source) using C++/CLI. The C++ library needs to call back the .NET delegate written in C++/CLI. I'm assigning a call back function to the C++ library classes using Marshal::GetFunctionPointerForDelegate. When this function is called back from the unmanaged side, however, I need to make sure that the .NET delegate function is still in the same memory location.</p> <p>The easiest way, of course, is to require the .NET library user to pin the .NET object but that's not really a clean design and also allows the user to shoot themselves in the foot. Better way is to design the .NET class so that it pins itself either at the time of creation or triggered by a function/event.</p> <p>How would I design this? According to this link, <a href="http://msdn.microsoft.com/en-us/library/18xa23yk%28v=VS.100%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/18xa23yk%28v=VS.100%29.aspx</a>, you can't have interior ~= pinned pointers as object members. This, then, implies that one could create a pinned pointer reference as either a static or a global variable.</p> <p>So I want to do something like either of these two but can't get it to compile/work.</p> <pre><code>public ref class UserClass{ void createDotNetCPPWrapperClass() { m_class = gcnew DotNetCPPWrapperClass; } DotNetCPPWrapperClass^ m_class }; public ref class DotNetCPPWrapperClass{ static pin_ptr&lt;DotNetCPPWrapperClass^&gt; pinnedSelf; DotNetCPPWrapperClass() { pinnedSelf = this; } }; </code></pre> <p>OR</p> <pre><code>public ref class UserClass{ void createDotNetCPPWrapperClass() { m_class = gcnew DotNetCPPWrapperClass; m_class-&gt;setupImportantStuff(); } DotNetCPPWrapperClass^ m_class }; public ref class DotNetCPPWrapperClass{ static pin_ptr&lt;DotNetCPPWrapperClass^&gt; pinnedSelf; DotNetCPPWrapperClass(){} void setupImportantStuff() { pinnedSelf = this; } }; </code></pre>
 

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