2

I have a c header file with the declaration

const char* GetTypeAsString(type_t type);

its docs say that it returns a pointer to null-terminated string which lays in static memory and should not be freed.

How do I structure a PInvoke declaration to call this function? I would like to have it like this:

[DllImport("lib", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Unicode)]
static extern string GetTypeAsString(TypeEnum type);

But I don't know how the Marshaler or the Runtime will handle the returned pointer i.e. if the returned string just gets the pointer to the and then sometime later the GC will try to free the memory.

Ackdari
  • 3,222
  • 1
  • 16
  • 33

1 Answers1

0

This should work:

Make the return type an IntPtr. And use Marshal.PtrToStringAuto to convert.

Stefan
  • 17,448
  • 11
  • 60
  • 79