是否有必要释放从 C# 接收的 C++ 中字符串的内存?
Posted
技术标签:
【中文标题】是否有必要释放从 C# 接收的 C++ 中字符串的内存?【英文标题】:Is it necessary to free the memory of strings in C++ received from C#? 【发布时间】:2020-12-05 17:53:40 【问题描述】:我在 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
的内存?
【问题讨论】:
【参考方案1】:不,C# 封送处理程序会为您处理这个问题。 char*
将在 PInvoke 调用的生命周期内有效。如果您的 C++ 代码希望拥有 char*
,您应该在 SerializeMesh
中复制一份。
Here 是字符串编组的入门。如果您确实需要使用const char*
,则可能需要将MarshalAsAttribute 设置为UnmanagedType.LPStr
。有关字符串编组行为的更多信息,请参阅 here。
Here 是另一个有用的参考,如果您想深入挖掘。
【讨论】:
以上是关于是否有必要释放从 C# 接收的 C++ 中字符串的内存?的主要内容,如果未能解决你的问题,请参考以下文章