[英]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.