当托管代码加载非托管代码时是否需要释放内存
有 2 个二进制文件。一种是本机/非托管 C++ dll,另一种是托管 c# exe。现在我正在做的是在 c++ dll 中编写一个函数,并使用 malloc 在其中分配内存。我导出了这个函数以供我的 C# 模块使用。
在 C++ 中我做了:
char* FunctionHavingAllocatedMemory(int i){
char* p = (char*)malloc(100);
.....
//use p and do not free it.
return p;
}
在 C# 中我做了:
[DllImport("C++.dll")]
private static extern string FunctionHavingAllocatedMemory(int i);
现在,我的问题是:是否需要在 C++ 模块中释放内存,或者 C# 模块会在函数返回时自动释放它。我为什么这么想是因为 c# 是托管模块,它会自动清理内存。
(虽然在 C++ 中释放内存很好,但我有一定的限制,我不能在 C++ 中释放内存。只是想了解更多有关托管应用程序及其处理内存管理的方式)。
There are 2 binaries. One is native/unmanaged C++ dll and other is managed c# exe. Now what I am doing is writing a function in c++ dll and allocated memory inside it using malloc. I exported this function to be used by my c# module.
In C++ I did:
char* FunctionHavingAllocatedMemory(int i){
char* p = (char*)malloc(100);
.....
//use p and do not free it.
return p;
}
In c# I did:
[DllImport("C++.dll")]
private static extern string FunctionHavingAllocatedMemory(int i);
Now, my question is: Is there any need to free memory in c++ module or c# module will automatically free it when function will return. Why I am thinking is since c# is managed module it will automatically cleanup the memory.
(Though it is good you free memory in c++ but I have certain constrained that I can not free memory in C++. Just wanted to understand more about managed applications and the way they handle memory management).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
垃圾收集器仅在托管堆上工作:您有责任释放在
FunctionHavingAlownedMemory
中分配的内存。The garbage collector only works on the managed heap : the memory allocated in
FunctionHavingAllocatedMemory
is your responsibility to free.或者,您可以使用
Marshal.AllocHGlobal()
在 C# 中分配非托管内存,将指向它的指针传递给本机 dll,然后将Marshal.FreeHGlobal()
返回到 C# 中。Marshal
类还具有一些将数据复制到分配的内存中或从分配的内存中获取数据的函数。Alternatively you could allocate the unmanaged memory in C# using
Marshal.AllocHGlobal()
, pass a pointer to it to your native dll andMarshal.FreeHGlobal()
it back in C#. TheMarshal
class also has some functions to copy data into or fetch data from the allocated memory.GC会负责管理内存,对于托管代码来说,对于非托管代码则需要担心如何回收内存。
我认为,您可以在 C++ 类中定义一个函数,该函数将在内部释放内存。
GC will responsible for managing memory for the managed code for unmanaged code you need to worry about how to reclaim memory.
i think , you can define a function in the c++ class which will internally release the memory.