简体   繁体   English

如何在 C# 中使用带有结构的 DLLImport 作为参数?

[英]How do I use DLLImport with structs as parameters in C#?

All the examples I can find using DLLImport to call C++ code from C# passes ints back and forth.我可以找到使用 DLLImport 从 C# 调用 C++ 代码的所有示例来回传递整数。 I can get those examples working just fine.我可以让这些例子工作得很好。 The method I need call takes two structs as its import parameters, and I'm not exactly clear how I can make this work.我需要调用的方法将两个结构作为其导入参数,我不太清楚如何使其工作。

Here's what I've got to work with:这是我必须使用的:

I own the C++ code, so I can make any changes/additions to it that I need to.我拥有 C++ 代码,因此我可以对其进行任何我需要的更改/添加。

A third party application is going to load my DLL on startup and expects the DLLExport to be defined a certain way, so i can't really change the method signature thats getting exported.第三方应用程序将在启动时加载我的 DLL 并期望 DLLExport 以某种方式定义,因此我无法真正更改导出的方法签名。

The C# app I'm building is going to be used as a wrapper so i can integrate this C++ piece into some of our other applications, which are all written in C#.我正在构建的 C# 应用程序将用作包装器,因此我可以将此 C++ 集成到我们的其他一些应用程序中,这些应用程序都是用 C# 编写的。

The C++ method signature I need to call looks like this我需要调用的 C++ 方法签名如下所示

DllExport int Calculate (const MathInputStuctType *input, 
    MathOutputStructType *output, void **formulaStorage)

And MathInputStructType is defined as the following并且 MathInputStructType 定义如下

typedef struct MathInputStuctTypeS {
    int             _setData;
    double              _data[(int) FieldSize];
    int             _setTdData;
} MathInputStuctType;

The MSDN topic Passing Structures has a good introduction to passing structures to unmanaged code. MSDN 主题传递结构很好地介绍了将结构传递给非托管代码。 You'll also want to look at Marshaling Data with Platform Invoke , and Marshaling Arrays of Types .您还需要查看Marshaling Data with Platform InvokeMarshaling Arrays of Types

From the declaration you posted, your C# code will look something like this:根据您发布的声明,您的 C# 代码将如下所示:

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

Depending on the structure of MathInputStructType and MathOutputStructType in C++, you are going to have to attribute those structure declarations as well so that they marshal correctly.根据 C++ 中 MathInputStructType 和 MathOutputStructType 的结构,您还必须对这些结构声明进行属性化,以便它们正确编组。

For the struct:对于结构:

struct MathInputStuctType 
{
    int       _setData;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = FieldSize)]
    double[]  _data;
    int       _setTdData;
}

You might want to look at this project on CodePlex, http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120 .您可能想查看 CodePlex 上的这个项目, http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120 It should help you marshal the structures correctly.它应该可以帮助您正确编组结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM