Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free unmanaged c-code memory in managed C#

I have a large c-code library that used to write its results to file. I converted it to return it's data via a float* array to a C++ program like such (to avoid constant file I/O):

float* mgrib(...)

This worked fine in c++ where I could "free" the memory. I managed to get the data into C# properly via:

IntPtr pointer = mgrib(...);
float[] result = new float[ size ];
Marshal.Copy( pointer, result, 0, size );
Marshal.FreeCoTaskMem( pointer );

This is within a loop as many fields must be pulled from the function. If it's less than 256 fields it works great. If it's more it crashes without warning. If I run a file through it properly then run another (totaling more than 256) it crashes. I'm far from a CS expert but the 256 seems like more than a coincidence.

I appreciate any insight. Thanks.

like image 477
Anthony Avatar asked Mar 09 '11 18:03

Anthony


1 Answers

First of all, are you sure the C++ library allocates the return-value buffer using CoTaskMemAlloc, so that you can free it using Marshall.FreeCoTaskMem? There are various memory (de)allocation functions and you cannot freely mix them.

That is the reason why libraries are very often designed to allocate and deallocate memory “on a single side”, e.g. use something like

void mgrib(..., float *buff, int buffsize);
like image 185
Mormegil Avatar answered Nov 01 '22 14:11

Mormegil