You cannot return a pointer to a local variable since those are allocated on the stack (and the stack may get destroyed when the function returns).
You’d need to allocate memory on the heap (preferably using CoTaskMemAlloc
so the CLR can free up the memory later) on your C function and return a pointer to that memory.
As a side note, you can directly return a string
when marshalling (assuming it’s a c null-terminated unicode string), no need to return IntPtr
.
More info here: http://limbioliong.wordpress.com/2011/06/16/returning-strings-from-a-c-api/
5
solved C# pinvoke of C function returning char* [duplicate]