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 ofgchandle.addrofpinnedobject()
? - is
string
correct data type (fordo_something
) in case? or should useintptr
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
Post a Comment