如何将DLLImport与结构一起用作C#中的参数?

我可以使用DLLImport从C#调用C ++代码的所有示例都来回传递。 我可以让这些例子正常工作。 我需要调用的方法将两个结构作为其导入参数,我并不清楚如何使其工作。

这是我必须要做的事情:

我拥有C ++代码,因此我可以对其进行任何更改/添加。

第三方应用程序将在启动时加载我的DLL并期望以某种方式定义DLLExport,因此我无法真正更改导出的方法签名。

我正在构建的C#app将被用作包装器,因此我可以将这个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主题Passing Structures很好地介绍了将结构传递给非托管代码。 您还需要查看使用平台调用的Marshaling数据和类型的Marshaling数组 。

从您发布的声明中,您的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。 它应该可以帮助你正确地编组结构。