c# - 如何以 32/64 位兼容方式在 C# 中定义 MAPINAMEID 结构?

标签 c# interop pinvoke

在 C 中,MAPINAMEID 定义为:

typedef struct _MAPINAMEID
{
    LPGUID lpguid;
    ULONG ulKind;
    union {
        LONG lID;
        LPWSTR lpwstrName;
    } Kind;

} MAPINAMEID, FAR * LPMAPINAMEID;

在C#中,我的定义是:

    [StructLayout(LayoutKind.Explicit)]
    private struct MAPINAMEID
    {
        [FieldOffset(0)]
        public IntPtr lpguid;
        [FieldOffset(8)]
        public uint ulKind;
        [FieldOffset(16)]
        public int lID;
        [FieldOffset(16)]
        public IntPtr lpwstrName;
    };

显然,它只能在 64 位模式下工作,对于 32 位模式我需要不同的偏移值。不幸的是,FieldOffset 属性不允许使用可计算值(如 IntPtr.Size)。是否有一种独立于平台的方法来指定偏移量(或者以其他方式告诉编译器我希望 lID 和 lpwstrName 共享相同的偏移量?

最佳答案

你可以这样声明:

[StructLayout(LayoutKind.Sequential)]
private struct MAPINAMEID
{
    public IntPtr lpguid;
    public uint ulKind;
    public IntPtr lpwstrName; // or lID
};

并在需要时使用 IntPtr 32 位转换在 lpwstrName 和 lId 之间切换(LONG 和 ULONG 是 32 位的)。

关于c# - 如何以 32/64 位兼容方式在 C# 中定义 MAPINAMEID 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49631349/

相关文章:

c# - 无法在 Unity 中将结构数组从 C++ 编码到 C#

c# - Android 上的 Xamarin.Forms ListView OutOfMemoryError 异常

c# - 从云服务中的 Azure 文件访问挂载

c# - 如何使用 office interop API 枚举 word 文档?

c++ - 来自变量的模板类型

c# - 如何在 C# 中编码 NDISUIO_QUERY_OID 结构以执行以下任务

c# - “agsXMPP.MessageGrabber”是 'type',但使用方式类似于 'variable'

c# - 在 C# 程序中从 Firefox 获取网页内容

c# - 如何通过zkemkeeper下载指定时间的考勤记录

c# - GetLogicalProcessorInformation 函数的 PInvoke