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:

  1. aside keeping instance of hopen, should pin it?

  2. should keep reference of flags variable? should pin since it's passed reference in particular case?

  3. 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?

  4. 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.

  1. no need pin hopen, has value type semantics.
  2. if dll writes address pointed flags, , after original function returns, need pin 1 way or (as keeping alive , safe clutches of gc).
  3. the callback function pointer pinned. need keep reference delegate alive, don't need pin because native thunk allocated unmanged heap.
  4. you don't need special here because passing intptr , memory behind pinned. don't need to keep reference string alive because disconnected intptr returned stringtohglobalansi. has copy of contents of string @ point of call stringtohglobalansi.

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

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -