如何在 C# 中定义 TBBUTTON 结构?

Pau*_*ano 1 c# 64-bit interop

问候大家,

TBBUTTON 结构在 MSDN 上定义如下:

typedef struct {
  int       iBitmap;
  int       idCommand;
  BYTE      fsState;
  BYTE      fsStyle;
#ifdef _WIN64
  BYTE      bReserved[6];
#else 
#if defined(_WIN32)
  BYTE      bReserved[2];
#endif 
#endif 
  DWORD_PTR dwData;
  INT_PTR   iString;
} TBBUTTON, *PTBBUTTON, *LPTBBUTTON;
Run Code Online (Sandbox Code Playgroud)

我需要使用这个结构在 C# 中做一些互操作。我如何复制这个怪物,以便在为 AnyCPU 编译时正确定义它?谷歌显然充满了危险的错误信息!

Pau*_*ano 5

啊哈,我知道必须有办法。这是:

[StructLayout(LayoutKind.Sequential)]
public struct TBBUTTON {
    public int iBitmap;
    public int idCommand;
    [StructLayout(LayoutKind.Explicit)]
    private struct TBBUTTON_U {
        [FieldOffset(0)] public byte fsState;
        [FieldOffset(1)] public byte fsStyle;
        [FieldOffset(0)] private IntPtr bReserved;
    }
    private TBBUTTON_U union;
    public byte fsState { get { return union.fsState; } set { union.fsState = value; } }
    public byte fsStyle { get { return union.fsStyle; } set { union.fsStyle = value; } }
    public UIntPtr dwData;
    public IntPtr iString;
}
Run Code Online (Sandbox Code Playgroud)

Marshal.SizeOf在 x64 进程上返回 32,在 x86 进程上返回 20,当我将它传递给SendMessage. 我知道你可以做到,C#!