If I want to call an external C++ function which returns a 2d array, what kind of problems could I come across? For instance, if I declare the 2D array inside of the C++ function and initialize the size of the array within the C++ function, how will the .Net automatic garbage collector handle this? Do I have to give it a function which performs garbage collection and if so how do I call it from a C# program?
Share
Unless the function returns a vector or vectors, it is the exact same problem in C++ as well. It is a memory management problem, the caller of the function has no good way to free the memory of the array, it doesn’t know the array sizes nor what allocator was used. For that matter, even iterating the array is perilous. A problem you can’t fix in C++ cannot be fixed in managed interop either.
And you solve it the same way, you let the caller provide the array, to be filled by the callee.
Note that managed arrays don’t have this problem, they are classes just like vector<>. Returning a managed array from a function is not an issue. C++/CLI can do it, the standard solution for difficult interop problems. A SAFEARRAY is also a solution, tell the P/Invoke marshaller about them with [MarshalAs] in the managed declaration.