0

我有一个需要从 C# 调用的第三方非托管 C++ dll。C++ 函数返回一个 char*。我已经想出了如何将其转换为 C# 中的托管字符串。但我不知道是否需要释放内存。以下代码有效,但 Marshal.FreeHGlobal(p) 抛出“句柄无效。”。那么我是否需要释放内存,如果需要,如何?

[DllImport("abc.dll", EntryPoint = "?GetVersion@ABC@@QEAAPEADXZ", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe char* GetVersionRaw();


public static unsafe string GetVersion()
{
    char* x = Abc.GetVersionRaw(); // call the function in the unmanaged DLL
    IntPtr p = new IntPtr(x);
    string s = Marshal.PtrToStringAnsi(p);
    Marshal.FreeHGlobal(p);
    return s;
}
4

1 回答 1

2

It is impossible to say in general how to free an arbitrary pointer returned from a C++ function. There are many ways the pointer could have been produced (new, malloc, VirtualAlloc when you're on Windows, etc). There is no way to determine by inspection which one the pointer came from, and using the wrong deallocation function is an error (which may crash your process). Also, even if you know which function to call, your code may be linked against a different version of the language runtime library - so you might be correctly calling free or delete, but an incompatible version.

Normal procedure is for libraries that perform allocation to provide a corresponding deallocation function that frees the allocated memory appropriately. If the library you're using doesn't have this, you'll just have to try what they've told you and follow up if it doesn't work.

于 2014-08-21T23:27:38.330 回答