[英]P/Invoke Struct with Pointers, C++ from C#
我試圖用結構和函數調用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);
}
我以為我已經很接近了,但是當我運行它時,程序只是在return語句中退出。
有什么想法我做錯了嗎?
謝謝,
標記
似乎您忘記了指定調用約定:
[DllImport("mydll.dll", EntryPoint="some_func", CallingConvention=CallingConvention.Cdecl)]
您是否已調試成some_func? 嘗試關閉該程序。 或使用VS,但請確保捕獲所有異常並啟用混合調試。
除了Ariel建議的內容外,我還建議一些其他內容。
return
之前將some_func(ref someData)
語句移至其自己的行。 Marshal.FreeHGlobal
(否則,這將導致內存泄漏)。 order
等於數組長度,我將繼續使用它。 我唯一建議的其他想法是在您的結構中使用double*
和/或使用fixed
語句fixed
數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.