当托管代码加载非托管代码时是否需要释放内存

发布于 2024-10-07 03:32:41 字数 588 浏览 0 评论 0原文

有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

病女 2024-10-14 03:32:41

垃圾收集器仅在托管堆上工作:您有责任释放在FunctionHavingAlownedMemory中分配的内存。

The garbage collector only works on the managed heap : the memory allocated in FunctionHavingAllocatedMemory is your responsibility to free.

送舟行 2024-10-14 03:32:41

或者,您可以使用 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 and Marshal.FreeHGlobal() it back in C#. The Marshal class also has some functions to copy data into or fetch data from the allocated memory.

海夕 2024-10-14 03:32:41

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文