简体   繁体   English

将具有嵌入式结构数组的结构编组为非托管代码

[英]Marshalling struct with embedded struct array to unmanaged code

I'm dealing with a commercial instrumentation DLL that has a C API, so that code can't be changed. 我正在处理具有C API的商业仪器DLL,因此无法更改代码。 We're using DLLIMPORT to use the API routines in C# code. 我们正在使用DLLIMPORT在C#代码中使用API​​例程。 One function takes a pointer to a complex struct, and this one isn't obvious to me whether we can marshal it. 一个函数需要一个指向复杂结构的指针,而对于我们是否可以将其编组,这对我来说并不明显。

typedef struct eibuf
{
   unsigned short buftype;
   struct
   {
      unsigned char etype;
      unsigned int edata;
   } error[33];
} EIBUF;

My research indicates that the only fixed arrays allowed in C# structs are those with primitive data, so I haven't been able to construct an equivalent data type. 我的研究表明,C#结构中允许的唯一固定数组是具有原始数据的数组,因此我无法构造等效的数据类型。

One way to handle this is to create an interface wrapper in C that will flatten the struct out to an array of integer type, which of course can then easily be marshaled from the C# code. 解决此问题的一种方法是在C中创建一个接口包装器,该包装器会将结构展平为整数类型的数组,然后当然可以轻松地将其从C#代码中整理出来。

The wrapper function would just declare an EIBUF variable and set all the fields from the array elements, then call the function from the instrumentation API with that. 包装函数将只声明一个EIBUF变量并设置数组元素中的所有字段,然后从检测API调用该函数。 That's kind of our default plan unless there's something more direct that can be done. 这是我们的默认计划,除非可以做一些更直接的事情。

Any thoughts? 有什么想法吗?

It is possible. 有可能的。 Just declare explicit struct type for your error items: 只需为您的错误项声明显式结构类型:

[StructLayout(LayoutKind.Sequential)]
struct ErrorDescriptor
{
      Byte etype;
      Uint32 edata;
}

[StructLayout(LayoutKind.Sequential)]
struct EIBUF
{
   Uint16 buftype;
   [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 33)]
   ErrorDescriptor[] error;
}

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

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