[英]How do I use DLLImport with structs as parameters in C#?
我可以找到使用 DLLImport 從 C# 調用 C++ 代碼的所有示例來回傳遞整數。 我可以讓這些例子工作得很好。 我需要調用的方法將兩個結構作為其導入參數,我不太清楚如何使其工作。
這是我必須使用的:
我擁有 C++ 代碼,因此我可以對其進行任何我需要的更改/添加。
第三方應用程序將在啟動時加載我的 DLL 並期望 DLLExport 以某種方式定義,因此我無法真正更改導出的方法簽名。
我正在構建的 C# 應用程序將用作包裝器,因此我可以將此 C++ 集成到我們的其他一些應用程序中,這些應用程序都是用 C# 編寫的。
我需要調用的 C++ 方法簽名如下所示
DllExport int Calculate (const MathInputStuctType *input,
MathOutputStructType *output, void **formulaStorage)
並且 MathInputStructType 定義如下
typedef struct MathInputStuctTypeS {
int _setData;
double _data[(int) FieldSize];
int _setTdData;
} MathInputStuctType;
MSDN 主題傳遞結構很好地介紹了將結構傳遞給非托管代碼。 您還需要查看Marshaling Data with Platform Invoke和Marshaling Arrays of Types 。
根據您發布的聲明,您的 C# 代碼將如下所示:
[DllImport("mydll.dll")]
static extern int Calculate(ref MathInputStructType input,
ref MathOutputStructType output, ref IntPtr formulaStorage);
根據 C++ 中 MathInputStructType 和 MathOutputStructType 的結構,您還必須對這些結構聲明進行屬性化,以便它們正確編組。
對於結構:
struct MathInputStuctType
{
int _setData;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = FieldSize)]
double[] _data;
int _setTdData;
}
您可能想查看 CodePlex 上的這個項目, http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120 。 它應該可以幫助您正確編組結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.