Here is my code in C++
struct myStruct
{
int cid;
float c;
float r;
};
int Predict(myStruct* p, const char* path2D)
{
std::vector<myStruct> result = SomeFunction(path2D);//e.g., result.size() = 2 here
for(unsigned int i = 0; result.size(); i++)
{
p[i] = result[i];
}
return 0;
}
extern "C"{
int __declspec(dllexport) Predict(myStruct* predictions, const char* path2D);
}
call inside the C#
[StructLayout(LayoutKind.Sequential)]
public struct myStruct
{
public int cid;
public float c;
public float r;
}
[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Predict([MarshalAs(UnmanagedType.LPArray)] ref myStruct[] results, [MarshalAs(UnmanagedType.LPStr)] string path2Image);
This code fails on execution. Any idea / suggestion would be helpful what might be wrong here?
Also when i debug the code it goes through C++ function Predict until return 0; after which it throws error.
Fatal error. Internal CLR error. (0x80131506)
Your code have several problems and suboptimal points.
You have an infinite loop
for(unsigned int i = 0; result.size(); i++)You do not need to copy your array (in native), instead you want to keep your array as a global object, and return the pointer to the
data()of the vector and then marshal it. This is the most general schema, in particular, if you have unblittable types and arrays, you can't do it differently.You are actually not just passing a struct from native to managed, but an array of struct, which is a bit more demanding.
If you are passing just one struct from native to managed, you only only need
Marshal.PtrToStructure<myStruct>(pointer);If you need to get a vector of structures, I advise you to marshal the structs one at a time on the managed side.
Here a functionnal revised code:
native:
managed:
result:
remarks:
you need to have a global instance, in order to keep the object alive; the alternative is to use the pointer of a class instance created by
new MyClass().the functions of your managed structure are not taken into account for your structure size; and with blittable types, the structure size is the same in managed and native.