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.
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.
How would I design this? According to this link, http://msdn.microsoft.com/en-us/library/18xa23yk%28v=VS.100%29.aspx, 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.
So I want to do something like either of these two but can't get it to compile/work.
public ref class UserClass{
void createDotNetCPPWrapperClass()
{
m_class = gcnew DotNetCPPWrapperClass;
}
DotNetCPPWrapperClass^ m_class
};
public ref class DotNetCPPWrapperClass{
static pin_ptr<DotNetCPPWrapperClass^> pinnedSelf;
DotNetCPPWrapperClass()
{
pinnedSelf = this;
}
};
OR
public ref class UserClass{
void createDotNetCPPWrapperClass()
{
m_class = gcnew DotNetCPPWrapperClass;
m_class->setupImportantStuff();
}
DotNetCPPWrapperClass^ m_class
};
public ref class DotNetCPPWrapperClass{
static pin_ptr<DotNetCPPWrapperClass^> pinnedSelf;
DotNetCPPWrapperClass(){}
void setupImportantStuff()
{
pinnedSelf = this;
}
};
GCHandle
orHandleRef
structures provided by the framework? – Cody Gray