c# - 如何通过 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 函数时应该如何转换它?
我读了一些关于编组的文章,但我还是不太明白,我不确定它是否可以在这里应用?
解决方案
您不能与 C++ 类(例如std::vector
)互操作,只能与基本的 C 样式数据类型和指针进行互操作。(作为旁注)这是微软在发明 COM 时试图解决的问题之一。
为了让它工作,你应该导出一个不同的函数,它接收纯 C 数组及其各自的长度:
C++ 端
extern "C" __declspec(dllexport) int MyExternMethod(
double *tissue, int tissueLen,
double *bg, int bgLen,
/* ... the rest ... */
);
// implementation
int MyExternMethod(
double* tissue, int tissueLen,
double* bg, int bgLen,
/* ... the rest ... */ )
{
// call your original method from here:
std::vector<double> tissueData(tissue, tissue + tissueLen);
std::vector<double> bgData(bg, bg + bgLen);
/* ... the rest ... */
return MyMethod(tissueData, bgData, /* ...the rest... */);
}
C# 端的互操作导入将是:
C#端
public static class MyLibMethods
{
[DllImport("MyLib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int MyExternMethod(
double[] tissue, int tissueLen,
double[] bg, int bgLen,
/*...the rest...*/
);
}
您可以像这样在 C# 中调用它:
C#端
public int CallMyExternMethod(double[] tissue, double[] bg, /*... the rest ...*/)
{
return MyLibMethods.MyExternMethod(
tissue, tissue.Length,
bg, bg.Length,
/*...the rest...*/
);
}
推荐阅读
- android - 如何从“doInBackground”返回多个响应
- linux - Delphi 10.3 Linux 独占文件访问
- angular - Angular 2 表单控件更新
- elasticsearch - 哪条日志消息表明索引是从 filebeat 发送到 elasticsearch?
- c# - 当用户仅提供某些字段时发布实体类
- android - 对 java.util.Calendar 感到困惑
- variables - 在ansible中使用python变量
- jquery - 如何使用节点接收 ajaxed 多部分表单数据
- python - 将 fit 文件转换为 healpix 地图
- oracle - 如何让用户在 Oracle 实时服务器的 PlSql 中输入值?