✅ passing a string to and from a native DLL with pinvoke?

I have some functions in a native dll that look something like this: (not exactly like this but this is the essential stuff) const char* get_string(); void free_string(const char *c); How would I define those in a C# program so I can get a C# string from the native char buffer and then get the native char buffer pointer so it can be freed?
4 Replies
jen
jen5w ago
dllimport and its better brother libraryimport
Jonathan Wilson
Jonathan WilsonOP5w ago
I know about dllimport, just don't know how to handle the strings.
jen
jen5w ago
not sure what you mean what part dont you know the c# side string is managed so it is not related to the c side string in any way
sibber
sibber5w ago
you use LibraryImport and specify StringMarshalling to the encoding of you native string and if its allocated in the unmanaged side and you want to pass ownership to managed, then you also need to expose a function to free it also, DllImport is legacy and shouldnt be used today

Did you find this page helpful?