是否有必要释放从 C# 接收到的 C++ 中的字符串内存?

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

我在 C++ 中公开了以下 DLL 函数。

// 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);

在 C# 中,我使用以下内容。

// 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);

SerializationError返回的IntPtr在C++中使用new分配。所以我有另一个 DLL 导出函数,它在被 C# 调用时释放指针。

我的问题是,在 C++ 中,我是否需要释放 SerializeMesh 参数中 const char * path 的内存?

不,C# 封送拆收器会为您解决这个问题。 char* 在 PInvoke 调用的生命周期内有效。如果您的 C++ 代码希望拥有 char*,您应该在 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 了解有关字符串封送处理行为的更多信息。

如果您想深入挖掘,

Here 是另一个有用的参考。