简体   繁体   English

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

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

I have the following exposed DLL functions in 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);

From C#, I use the following.从 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);

The IntPtr returned by SerializationError is allocated using new in C++. SerializationError返回的IntPtr使用 C++ 中的new分配。 So I have another DLL exported function that frees the pointer when called by C#.所以我有另一个 DLL 导出的 function 在被 C# 调用时释放指针。

My question is, do I need to free the memory of the const char * path in the argument of SerializeMesh in C++?我的问题是,我是否需要在 C++ 的SerializeMesh参数中释放const char * path的 memory?

No, the C# marshaler will take care of this for you.不,C# 封送器会为您解决这个问题。 The char* will be valid during the lifetime of the PInvoke call. char*将在 PInvoke 调用的生命周期内有效。 If your C++ code expects to own the char* , you should make a copy in SerializeMesh .如果您的 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 .如果您确实需要使用const char* ,则可能需要将MarshalAsAttribute设置为UnmanagedType.LPStr See here for more information on string marshaling behavior.有关字符串编组行为的更多信息,请参见此处

Here is another useful reference if you want to dig even deeper.如果您想更深入地挖掘, 是另一个有用的参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM