的PInvoke:如何释放一个malloc分配的字符串? [英] pinvoke: How to free a malloc'd string?

查看:255
本文介绍了的PInvoke:如何释放一个malloc分配的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个C DLL,我有这样的功能:

 的char * GetSomeText(字符* szInputText)
{
      字符* ptrReturnValue =(字符*)malloc的(strlen的(szInputText)* 1000); //其实parsemarkup后进行的适当的长度
      init_parser(); //分配的ParseMarkup结果的内部处理的缓冲区,这是我需要复制
      sprintf的(ptrReturnValue,%S,ParseMarkup(szInputText));
      terminate_parser(); //释放内部处理缓冲区
      返回ptrReturnValue;
}
 

我想,使用P从C#调用它/调用。

  [的DllImport(MYDLL.DLL)
私人静态外部串GetSomeText(字符串strInput);
 

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

我写的跨平台code针对Windows和Linux操作系统。

编辑: 像这样

  [的DllImport(MYDLL.DLL)
私人静态外部System.IntPtr GetSomeText(字符串strInput);

[的DllImport(MYDLL.DLL)]
私人静态外部无效FreePointer(System.IntPtr ptrInput);

IntPtr的PTR = GetSomeText(SomeText);
字符串结果= Marshal.PtrToStringAuto(PTR);
FreePointer(PTR);
 

解决方案

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

此看到几乎(但不完全)的C函数重复的问题 PInvoke的是返回的char *

在理想情况下你的C DLL也应该公开一个 FreeText的功能,让你当你想释放字符串中使用。这确保了该字符串被释放以正确的方式(即使C的dll变化)。

In a C dll, I have a function like this:

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;
}

I would like to call it from C# using P/invoke.

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

How do I properly release the allocated memory?

I am writing cross-platform code targeting both Windows and Linux.

Edit: Like this

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

解决方案

You should marshal returned strings as IntPtr otherwise the CLR may free the memory using the wrong allocator, potentially causing heap corruption and all sorts of problems.

See this almost (but not quite) duplicate question PInvoke for C function that returns char *.

Ideally your C dll should also expose a FreeText function for you to use when you wish to free the string. This ensures that the string is deallocated in the correct way (even if the C dll changes).

这篇关于的PInvoke:如何释放一个malloc分配的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆