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

Jon*_*ter 9 c# c++

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

这是我必须要做的事情:

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

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

我正在构建的C#app将用作包装器,因此我可以将这个C++片段集成到我们的其他一些应用程序中,这些应用程序都是用C#编写的.

我需要调用的C++方法签名看起来像这样

DllExport int Calculate (const MathInputStuctType *input, 
    MathOutputStructType *output, void **formulaStorage)
Run Code Online (Sandbox Code Playgroud)

MathInputStructType定义如下

typedef struct MathInputStuctTypeS {
    int             _setData;
    double              _data[(int) FieldSize];
    int             _setTdData;
} MathInputStuctType;
Run Code Online (Sandbox Code Playgroud)

Jim*_*hel 10

MSDN主题Passing Structures很好地介绍了将结构传递给非托管代码.您还需要查看使用平台调用的Marshaling数据Marshaling类型数组.


cas*_*One 5

从您发布的声明来看,您的 C# 代码将如下所示:

[DllImport("mydll.dll")]
static extern int Calculate(ref MathInputStructType input,
    ref MathOutputStructType output, ref IntPtr formulaStorage);
Run Code Online (Sandbox Code Playgroud)

根据 C++ 中 MathInputStructType 和 MathOutputStructType 的结构,您还必须对这些结构声明进行属性处理,以便它们正确编组。