我试图使用结构和函数调用C ++ dll,如
struct some_data{
int size,degree,df,order;
double *x,*y,lambda;
};
extern "C"{
__declspec(dllexport) double *some_func(some_data*);
}
来自C#:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct SOME_DATA
{
public int size;
public int degree;
public int df;
public int order;
public System.IntPtr x;
public System.IntPtr y;
public double lambda;
}
[System.Runtime.InteropServices.DllImportAttribute("mydll.dll",EntryPoint="some_func")]
public static extern System.IntPtr some_func(ref SOME_DATA someData);
public IntPtr some_funcCall(){
double[] x = new double[] { 4, 4, 7, 7 };
double[] y = new double[] { 2, 10, 4, 22 };
SOME_DATA someData = new SOME_DATA();
someData.x = Marshal.AllocHGlobal(x.Length * Marshal.SizeOf(typeof(double)));
Marshal.Copy(x, 0, someData.x, x.Length);
someData.y = Marshal.AllocHGlobal(y.Length * Marshal.SizeOf(typeof(double)));
Marshal.Copy(y, 0, someData.y, y.Length);
someData.size = 50;
someData.degree = 3;
someData.df = 50;
someData.order = 4;
someData.lambda = 1;
return some_func(ref someData);
}
我认为我非常接近,但是当我运行它时,程序就会退回到返回语句。
我出错的任何想法?
谢谢,
标记
答案 0 :(得分:1)
好像你忘了指定调用约定:
[DllImport("mydll.dll", EntryPoint="some_func", CallingConvention=CallingConvention.Cdecl)]
答案 1 :(得分:0)
你调试过some_func吗?尝试windbg该程序。或者使用VS,但要确保捕获所有异常并启用混合调试。
答案 2 :(得分:0)
我会推荐一些超出Ariel建议的东西。
some_func(ref someData)
语句移至return
。Marshal.FreeHGlobal
(否则,这将是内存泄漏)。order
等于数组长度,我会继续使用它。我建议的唯一其他想法是在结构中使用double*
和/或使用fixed
语句固定数组。