3

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

icecrime
  • 74,451
  • 13
  • 99
  • 111
Supernova009
  • 95
  • 1
  • 7

3 Answers3

2

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

icecrime
  • 74,451
  • 13
  • 99
  • 111
2

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.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
0

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.

TalentTuner
  • 17,262
  • 5
  • 38
  • 63