如何正确地将结构从 C++ 传递到 C#?

问题描述 投票:0回答:0

这是我的 C++ 代码

struct myStruct
{
    int cid;
    float c;
    float r;
};

int Predict(myStruct* p, const char* path2D)
{
    std::vector<myStruct> result = SomeFunction(path2D);
    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);
          }

在 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);

此代码执行失败。任何想法/建议都会有所帮助,这里可能出了什么问题?

另外,当我调试代码时,它会通过 C++ 函数 Predict 直到返回 0;之后它会抛出错误。

Fatal error. Internal CLR error. (0x80131506)
c# c++ unmanaged managed
© www.soinside.com 2019 - 2024. All rights reserved.