从管理code免费托管内存分配 [英] Free unmanaged memory allocation from managed code

查看:188
本文介绍了从管理code免费托管内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个.NET应用程序调用C DLL。在C code代表一个字符数组分配内存,并返回该数组作为结果。在.NET应用程序得到这个结果作为一个字符串。

A .NET application calls C dll. The C code allocates memory for a char array and returns this array as result. The .NET applications gets this result as a string.

在C code:

extern "C" __declspec(dllexport) char* __cdecl Run()
{
    char* result = (char*)malloc(100 * sizeof(char));
    // fill the array with data
    return result;
}

在C#code:

The C# code:

[DllImport("Unmanaged.dll")]
private static extern string Run();

...
string result = Run();
// do something useful with the result and than leave it out of scope

它的一些测试表明,垃圾回收器不会释放由C code分配的内存。

Some tests of it show that the garbage collector does not free the memory allocated by the C code.

任何帮助将AP preciated。 :)

Any help will be appreciated. :)

推荐答案

托管字符串是不一样的char *。会发生什么事是卧底的编组code的互操作层,使非托管字符串拷贝,以将其转换为托管字符串,但不能释放的内存,因为它不知道它是怎么分配的。

Managed string is not the same as char*. What happens undercover is that the marshaling code in the interop layer makes a copy of the unmanaged string in order to convert it to a managed string, but it can't free that memory as it does not know how it was allocated.

不过,你可以尝试分配并返回一个字符的BSTR而不是*。互操作层处理的方式与自动化的数据类型比传统的非托管数据类型更好。

However, you could try allocating and returning a BSTR instead of a char*. The interop layer deals way better with automation datatypes than classic unmanaged data types.

之所以重要的是炭方式*和BSTRs被分配在存储器

The reason why that matters is the way char* and BSTRs are allocated in the memory.

该字符*缓冲区分配使用专用分配/释放例程的CLR一无所知C ++运行时的堆,所以没有办法就可以删除的记忆。而为了让事情变得更糟糕的是,char *之分缓冲区可以通过内部堆实现的DLL code分配的,或者甚至可能指向成员变量的私有类。

The char* buffers are allocated on the heap of the C++ runtime using private allocation/deallocation routines that the CLR knows nothing about, so there's no way it can delete that memory. And to make things even worse, the buffer that char* points can be allocated by an internal heap implementation of the dll code, or it might even point to a member variable in a private class.

在另一方面,BSTRs使用Windows API SysAllocString分配,并释放了SyFreeStirng并且由于CLR互操作层知道这些Windows的API,它知道如何释放一个BSTR它从非托管code了。

The BSTRs on the other hand are allocated using the WIndows API SysAllocString and are freed by SyFreeStirng and since the CLR interop layer knows about these Windows APIs, it knows how to free a BSTR it got from unmanaged code.

这篇关于从管理code免费托管内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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