猿问

如何通过 DllImport 将双精度数组从 C# 传递到 C++

我有一个 C++ 函数,其方法签名为

MyMethod(std::vector<double> tissueData, std::vector<double> BGData, std::vector<double> TFData, std::vector<double> colMeans, std::vector<double> colStds, std::vector<double> model)

我希望通过 dllimport 在 C# 中调用这个 C++ 函数。在创建 dll 库时,我已将 C++ 端的函数定义为

extern "C" __declspec(dllexport) int MyMethod(double *tissue, double *bg, double *tf, double *colMeans, double *colStds, double* model);

我计划将一个双精度数组从 c# 端传递到 c++ dll 函数。但是,我不确定应该如何从 C# 端定义 DllImport 以及当我将其解析为 dllImport 函数时应该如何转换双精度数组?

我读了一些关于编组的内容,但我仍然不太明白,我不确定它是否可以应用在这里?


千巷猫影
浏览 148回答 1
1回答

冉冉说

您不能与 C++ 类(例如std::vector)进行互操作,只能与基本的 C 样式数据类型和指针进行互操作。(作为旁注)这是 Microsoft 在发明 COM 时试图解决的问题之一。为了使其工作,您应该导出一个不同的函数,该函数接收纯 C 数组及其各自的长度:C++端extern "C" __declspec(dllexport) int MyExternMethod(&nbsp; &nbsp; double *tissue, int tissueLen,&nbsp;&nbsp; &nbsp; double *bg, int bgLen,&nbsp; &nbsp; /* ... the rest ... */);// implementationint MyExternMethod(&nbsp; &nbsp; double* tissue, int tissueLen,&nbsp;&nbsp; &nbsp; double* bg, int bgLen,&nbsp; &nbsp; /* ... the rest ... */ ){&nbsp; &nbsp; // call your original method from here:&nbsp; &nbsp; std::vector<double> tissueData(tissue, tissue + tissueLen);&nbsp; &nbsp; std::vector<double> bgData(bg, bg + bgLen);&nbsp; &nbsp; /* ... the rest ... */&nbsp; &nbsp; return MyMethod(tissueData, bgData, /* ...the rest... */);}C# 端的互操作导入为:C#端public static class MyLibMethods{&nbsp; &nbsp; [DllImport("MyLib.dll", CallingConvention = CallingConvention.Cdecl)]&nbsp; &nbsp; public static extern int MyExternMethod(&nbsp; &nbsp; &nbsp; &nbsp; double[] tissue, int tissueLen,&nbsp; &nbsp; &nbsp; &nbsp; double[] bg, int bgLen,&nbsp; &nbsp; &nbsp; &nbsp; /*...the rest...*/&nbsp; &nbsp; );}你可以在 C# 中这样调用它:C#端public int CallMyExternMethod(double[] tissue, double[] bg, /*... the rest ...*/){&nbsp; &nbsp; return MyLibMethods.MyExternMethod(&nbsp; &nbsp; &nbsp; &nbsp; tissue, tissue.Length,&nbsp; &nbsp; &nbsp; &nbsp; bg, bg.Length,&nbsp; &nbsp; &nbsp; &nbsp; /*...the rest...*/&nbsp; &nbsp; );}
随时随地看视频慕课网APP
我要回答