我有一个带有方法签名的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样式数据类型和指针进行互操作。(作为旁注)这是Microsoft发明COM时试图解决的问题之一。
为了使其工作,您应该导出一个不同的函数,该函数接收纯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#端的互操作导入为:
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#中调用它:
public int CallMyExternMethod(double[] tissue, double[] bg, /*... the rest ...*/)
{
return MyLibMethods.MyExternMethod(
tissue, tissue.Length,
bg, bg.Length,
/*...the rest...*/
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句