Search code examples
c#c++memory-leaksinteropmarshalling

Is it necessary to free the memory of strings in C++ received from C#?


I have the following exposed DLL functions in C++.

// center_of_rotation_api.h
// CENTER_OF_ROTATION_API is a macro like __cdecl(dllexport) on Windows
CENTER_OF_ROTATION_API void SerializeMesh(Mesh * mesh, const char * path);
CENTER_OF_ROTATION_API const char * SerializationError(Mesh * mesh);

From C#, I use the following.

// dll is the name of the compiled dll
    [DllImport(dll)]
    public static extern void SerializeMesh(IntPtr mesh, string path);
    [DllImport(dll)]
    public static extern IntPtr SerializationError(IntPtr mesh);

The IntPtr returned by SerializationError is allocated using new in C++. So I have another DLL exported function that frees the pointer when called by C#.

My question is, do I need to free the memory of the const char * path in the argument of SerializeMesh in C++?


Solution

  • No, the C# marshaler will take care of this for you. The char* will be valid during the lifetime of the PInvoke call. If your C++ code expects to own the char*, you should make a copy in SerializeMesh.

    Here is a primer on string marshaling. If you really need to use a const char*, you might need to set the MarshalAsAttribute to UnmanagedType.LPStr. See here for more information on string marshaling behavior.

    Here is another useful reference if you want to dig even deeper.