【发布时间】:2015-03-28 17:17:42
【问题描述】:
我正在尝试为一些 Windows setupapi 调用编写良好的 P/Invoke 签名,但我在打包 setupapi 的结构时遇到了以下问题:
// Excerpt from setupapi.h
#if defined(_WIN64)
#include <pshpack8.h> // Assume 8-byte (64-bit) packing throughout
#else
#include <pshpack1.h> // Assume byte packing throughout (32-bit processor)
#endif
现在,这意味着我不能只将 StructLayoutAttribute.Pack 属性设置为常量值。
我尝试了以下操作:
[StructLayout(LayoutKind.Sequential, Pack = Environment.Is64BitProcess ? 8 : 1)]
public struct SP_DEVINFO_DATA
{
public uint cbSize;
public Guid ClassGuid;
public uint DevInst;
public IntPtr Reserved;
}
正如预期的那样,这会失败并出现以下编译错误:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
我真的很想避免#if 并设置不同的编译平台,而不是Any CPU。我可以在运行时确定 C# 结构的打包吗?
【问题讨论】: