开发者

Is there a need to free memory in unmanaged code when it is loaded by managed code

开发者 https://www.devze.com 2023-01-29 15:58 出处:网络
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 fun

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).


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消