如何释放非托管代码的内存

springontime 2015-12-06 11:10:54
有个问题比较困惑,非托管c++中有如下代码;
INF_APP bool GetTestDateTime(char** TestDateTime)
{

char source[100] = "ceshishuzhu";
char* pstr= new char[100];
memcpy_s(pstr,100,source,100);

*TestDateTime = pstr;
return true;
}

在C#中调用方式如下:
[DllImport("InfParser.dll", EntryPoint = "GetTestDateTime", CallingConvention = CallingConvention.Cdecl)]
public static extern bool GetTestDateTime(ref IntPtr TestDateTime);

String testtime = string.Empty;
IntPtr ptr = new IntPtr();
bool bRet = NativeMethod.GetTestDateTime(ref ptr);
testtime = Marshal.PtrToStringAnsi(ptr);

程序运行,没问题,可是c++函数中new的内存没有机会去释放,会有内存泄漏。请问这种情况如何释放那个临时分配的内存呢?
...全文
179 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2015-12-07
  • 打赏
  • 举报
回复
谁申请谁释放 用dispose模式,C++再定义一个方法,里面写delete,然后C#的dispose方法去调用
  • 打赏
  • 举报
回复
你应该去问写这个c++代码的人,问问他到底有没有这个考虑。在.net 中扯不上“释放非托管代码”的职责问题,完全是你引用的dll的开发者必须自己负责的事情。而且这个“释放”也绝非什么简单方便就能做到的,需要在c++代码中一点点“细抠”无遗漏地去单独编码。因此你在一个.net程序中,纠结这个是完全不应该的。
Poopaye 2015-12-06
  • 打赏
  • 举报
回复
这么写,那c++里也必须有释放的函数啊

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧