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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With