I have a DLL from which I need to P/Invoke the following C method:
int DAOpen(HANDLE *hOpen, UNIT *flags, void *callback, char *userData)
I’ve come up with the following C# signature:
[DllImportAttribute("<libName>", EntryPoint="DAOpen")]
static extern int DAOpen(
out IntPtr hOpen,
ref uint flags,
IntPtr callback,
IntPtr userData);
Assuming the native code keeps a reference to all parameters for longer than the duration of the P/Invoke call:
-
Aside from keeping an instance of the
hOpen, should I also pin it? -
Should I keep a reference of the
flagsvariable? Should I also pin it since it’s passed as a reference in this particular case? -
I’m assigning my
callbackdelegate in the following way:private IntPtr callBackOnNativeEvents;
...
this.callBackOnNativeEvents = Marshal.GetFunctionPointerForDelegate(
new CallBack(this.CallBackOnNativeEvents));Should I keep a reference to the delegate in itself (not only the pointer)? Should I also pin it?
-
Finally, I’m defining the
userDataparameter in the following way:private IntPtr userData;
...
string userName = "test";
this.userData = Marshal.StringToHGlobalAnsi(userName);Should I keep a reference to the string? Should I also pin it? The API documentation states that it copies the string content to unmanaged memory, but I’m not sure if it copies the content of the reference.
hOpen, it has value type semantics.flags, and does so after the original function returns, then you need to pin it one way or another (as well as keeping it alive and safe from the clutches of the GC).IntPtrand the memory behind that is pinned. You don’t need to to keep a reference to the string alive because it is completely disconnected from theIntPtrreturned byStringToHGlobalAnsi. It just has a copy of the contents of the string at the point of call toStringToHGlobalAnsi.I have to say that I am still incredulous that this DLL really could be doing what you say it is doing. I suspect that something else is going wrong which you are mis-diagnosing as the DLL holding onto pointer parameters from one call and then modifying their contents during subsequent calls. I find that exceptionally hard to believe, but of course only you can really know. If I was in your position I would simply ask the question of the DLL vendor.