pinvoke:如何释放malloc'd字符串?

Ste*_*ger 9 .net c c# mono pinvoke

在C dll中,我有这样的函数:

char* GetSomeText(char* szInputText)
{
      char* ptrReturnValue = (char*) malloc(strlen(szInputText) * 1000); // Actually done after parsemarkup with the proper length
      init_parser(); // Allocates an internal processing buffer for ParseMarkup result, which I need to copy
      sprintf(ptrReturnValue, "%s", ParseMarkup(szInputText) );
      terminate_parser(); // Frees the internal processing buffer
      return ptrReturnValue;
}
Run Code Online (Sandbox Code Playgroud)

我想使用P/invoke从C#中调用它.

[DllImport("MyDll.dll")]
private static extern string GetSomeText(string strInput);
Run Code Online (Sandbox Code Playgroud)

如何正确释放分配的内存?

我正在编写针对Windows和Linux的跨平台代码.

编辑:像这样

[DllImport("MyDll.dll")]
private static extern System.IntPtr GetSomeText(string strInput);

[DllImport("MyDll.dll")]
private static extern void FreePointer(System.IntPtr ptrInput);

IntPtr ptr = GetSomeText("SomeText");
string result = Marshal.PtrToStringAuto(ptr);
FreePointer(ptr);
Run Code Online (Sandbox Code Playgroud)

Jus*_*tin 7

您应该封送返回的字符串,IntPtr否则CLR可能会使用错误的分配器释放内存,从而可能导致堆损坏和各种问题.

看到这个几乎(但不完全)重复的问题PInvoke for C函数返回char*.

理想情况下FreeText,当您希望释放字符串时,您的C dll还应该公开一个函数供您使用.这可确保以正确的方式释放字符串(即使C dll更改).