c# - What to pass for pinned string in P/Invoke? -


assume c function:

void do_something(const char* str) 

it stores string somewhere later reference.

furthermore, have signature in c# call function:

[dllimport("nativelib")] static extern void do_something(string str); 

now, need when passing string method:

  • do need pin string (with gchandle.alloc()) (or marshaller creating copy)?
  • if need pin it, pass "original" string (i.e. string passed gchandle.alloc())? or need pass return value of gchandle.addrofpinnedobject()?
  • is string correct data type (for do_something) in case? or should use intptr instead?

storing pointers through interop boundary bad idea, can modify c code make copy of string instead.

pinning string suggested in upvoted answer isn't going work, pinvoke marshaller must convert string char* , releases converted string after making native call, invalidating pointer. must marshal string yourself. declare argument intptr , use marshal.stringtohglobalansi() create pointer value.

or use marshal.stringtocotaskmemansi(), allocates com heap. real problem, there no great scenario release string. c code cannot release string because doesn't know how allocated. c# code cannot release string because doesn't know when c code done pointer. why copying string important. can live memory leak if make call few times.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -