What happens when I allocate memory (structs within double pointer) in C++ and use it via Marshall with C#?
Do I have to clean up the memory or does the C# GarbageCollection do it for me? Marshall.FreeHGlobal(vsResult);
doesn't work.
[StructLayout(LayoutKind.Sequential)]
public struct MyCppResults
{
[MarshalAs(UnmanagedType.I4)] public int ResultSize;
public unsafe double* Result;
}
[DllImport("SomeVeryFastAlgorithm.dll")]
public static extern double[] LoadResults()
{
var resultsPtr = GetResults();
var vsResult = Marshal.PtrToStructure<MyCppResults>(resultsPtr);
var resultMatrix = new double[vsResult.ResultSize];
unsafe
{
for (var i = 0; i < resultMatrix.Length; i++)
resultMatrix[i] = vsResult.Result[i];
}
return resultMatrix;
}
As Marshall.FreeHGlobal
notes, this works in conjunction with AllocHGlobal
. It doesn't work in conjunction with C++ new[]
.
The memory allocated by new[]
is almost certainly allocated by the C++ Standard Library (if not, it's owned by a user-defined override). This must be returned by delete[]
.
You can call back from C# to C++ to tell it to call delete[]
. A logical location would be the C# destructor (finalizer).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.