There is a C++ library which contains
- structure
SimpleStruct - function
GetSimpleStructsreturning pointer to array of this structs
Like this:
typedef struct {
int value1;
int value2;
int value3;
} SimpleStruct;
extern SimpleStruct *GetSimpleStructs(int *count);
I have this implementation in C# .Net Core project:
[StructLayout(LayoutKind.Sequential)]
struct SimpleStruct
{
int value1;
int value2;
int value3;
}
[DllImport(LibName)]
public static extern IntPtr GetSimpleStructs(out int count);
And function that converts IntPtr to SimpleStruct[]:
SimpleStruct[] GetSimpleStructs()
{
var ptrToArray = GetSimpleStructs(out var count);
var arrayOfPtrs = new IntPtr[count];
var resultArray = new SimpleStruct[count];
Marshal.Copy(ptrToArray, arrayOfPtrs, 0, count);
for (var i = 0; i < count; i++)
resultArray[i] = Marshal.PtrToStructure<SimpleStruct>(arrayOfPtrs[i]); // HERE
return resultArray;
}
Everything works ok before the line with // HERE. In the first iteration program just finishes with exit code 139 without any exceptions.
So what am I doing wrong?
Also, I don't have the ability to reference project with struct in the project with DllImport