c++ 如何在C#中使用DLLImport并将结构体作为参数?

chy5wohz  于 2023-06-25  发布在  C#
关注(0)|答案(4)|浏览(189)

我能找到的所有使用DLLImport从C#调用C代码的例子都来回传递int。我可以让这些例子工作得很好。我需要调用的方法将两个结构体作为其导入参数,我不太清楚如何实现这一点。
这是我要做的
我拥有C
代码,所以我可以对它进行任何我需要的更改/添加。
第三方应用程序将在启动时加载我的DLL,并期望DLLExport以某种方式定义,所以我不能真正更改导出的方法签名。
我正在构建的C#应用程序将被用作 Package 器,因此我可以将此C片段集成到我们的其他一些应用程序中,这些应用程序都是用C#编写的。
我需要调用的C
方法签名如下所示

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

MathInputStructType定义如下

  1. typedef struct MathInputStuctTypeS {
  2. int _setData;
  3. double _data[(int) FieldSize];
  4. int _setTdData;
  5. } MathInputStuctType;
bvpmtnay

bvpmtnay1#

MSDN主题Passing Structures很好地介绍了如何将结构传递给非托管代码。您还需要查看Marshaling Data with Platform InvokeMarshaling Arrays of Types

zed5wv10

zed5wv102#

从你发布的声明中,你的C#代码看起来像这样:

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

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

kmb7vmvb

kmb7vmvb3#

对于结构:

  1. struct MathInputStuctType
  2. {
  3. int _setData;
  4. [MarshalAs(UnmanagedType.ByValArray, SizeConst = FieldSize)]
  5. double[] _data;
  6. int _setTdData;
  7. }
mznpcxlj

mznpcxlj4#

你可能想在CodePlex上看看这个项目,http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120。它应该可以帮助您正确地编组结构。

相关问题