c# - In which cases should parameters be pinned when performing a P/Invoke call -
i have dll need p/invoke following c method:
int daopen(handle *hopen, unit *flags, void *callback, char *userdata)
i've come following c# signature:
[dllimportattribute("<libname>", entrypoint="daopen")] static extern int daopen( out intptr hopen, ref uint flags, intptr callback, intptr userdata);
assuming native code keeps reference parameters longer duration of p/invoke call:
aside keeping instance of
hopen
, should pin it?should keep reference of
flags
variable? should pin since it's passed reference in particular case?i'm assigning
callback
delegate in following way:private intptr callbackonnativeevents;
...
this.callbackonnativeevents = marshal.getfunctionpointerfordelegate(
new callback(this.callbackonnativeevents));
should keep reference delegate in (not pointer)? should pin it?
finally, i'm defining
userdata
parameter in following way:private intptr userdata;
...
string username = "test";
this.userdata = marshal.stringtohglobalansi(username);
should keep reference string? should pin it? api documentation states copies string content unmanaged memory, i'm not sure if copies content of reference.
- no need pin
hopen
, has value type semantics. - if dll writes address pointed
flags
, , after original function returns, need pin 1 way or (as keeping alive , safe clutches of gc). - the callback function pointer pinned. need keep reference delegate alive, don't need pin because native thunk allocated unmanged heap.
- you don't need special here because passing
intptr
, memory behind pinned. don't need to keep reference string alive because disconnectedintptr
returnedstringtohglobalansi
. has copy of contents of string @ point of callstringtohglobalansi
.
i have still incredulous dll doing doing. suspect else going wrong mis-diagnosing dll holding onto pointer parameters 1 call , modifying contents during subsequent calls. find exceptionally hard believe, of course can know. if in position ask question of dll vendor.
Comments
Post a Comment