C# Interop: How to handle a char* to static memory that should not be freed

Viewed 51

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.

1 Answers
Related