如何将双精度数组从 C# 传递到 C++ (DLL)

How to pass Array of doubles from C# to C++ (DLL)

C++ 函数签名是:

int Eye_GetPositionSC2(std::string fname_mob, double sensors[9], int &map_x, int &map_y)

C# 函数签名是:

[DllImport(@"eyeWhere.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int Eye_GetPositionSC2([MarshalAs(UnmanagedType.LPWStr)]string filename, [In , MarshalAs(UnmanagedType.LPArray)]double[] sensors)

代码编译良好,但在将双精度数组传递给函数时存在 "AccessViolationexception"。

您不能从 C# 调用该函数。它接受不能用于互操作的 std::string。您还从 C# 翻译中省略了两个参数。

C++代码应该是:

int Eye_GetPositionSC2(
    const wchar_t* filename, 
    double sensors[9], 
    int &map_x, 
    int &map_y
)

C# 代码应该是:

[DllImport(@"eyeWhere.dll", CallingConvention = CallingConvention.Cdecl,
    CharSet = CharSet.Unicode)]
public static extern int Eye_GetPositionSC2(
    string filename, 
    [In, MarshalAs(UnmanagedType.LPArray, SizeConst = 9)]
    double[] sensors,
    ref int map_x,
    ref int map_y
)