结构大小,检查是64位还是32位

Roh*_*est 3 c#

我有一个Windows应用程序执行一个简单的例程来确定是否存在USB令牌.该方法始终在32位计算机上正常工作,但在64位计算机上进行测试时,我们开始看到意外结果.

我打电话给以下方法

[StructLayout(LayoutKind.Sequential)]
internal struct SP_DEVINFO_DATA
{
    public Int32 cbSize;
    public Guid ClassGuid;
    public Int32 DevInst;
    public UIntPtr Reserved;
};

[DllImport("setupapi.dll")] 
internal static extern Int32 SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, Int32 MemberIndex, ref  SP_DEVINFO_DATA DeviceInterfaceData);
Run Code Online (Sandbox Code Playgroud)

SP_DEVINFO_DATA结构的文档告诉我们cbSizeSP_DEVINFO_DATA结构的大小(以字节为单位).

如果我们计算32位机器的cbSize,那么对于64位机器,它将是28和32.

我已经通过使用不同的cbSize值重新编译在两台机器上测试了这个,我想知道的是我如何计算它作为运行时?我的应用程序需要在两种架构上运行.

internal static Int32 GetDeviceInfoData(Int32 iMemberIndex)
{
    _deviceInfoData = new Win32DeviceMgmt.SP_DEVINFO_DATA
    {
        cbSize = ?? // 28 When 32-Bit, 32 When 64-Bit,
        ClassGuid = Guid.Empty,
        DevInst = 0,
        Reserved = UIntPtr.Zero
    };

    return Win32DeviceMgmt.SetupDiEnumDeviceInfo(_deviceInfoSet, iMemberIndex, ref _deviceInfoData);
}
Run Code Online (Sandbox Code Playgroud)

谢谢

罗汉

Han*_*ant 9

使用Marshal.SizeOf:

_deviceInfoData = new Win32DeviceMgmt.SP_DEVINFO_DATA
    {
        cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA);
        // etc..
    }
Run Code Online (Sandbox Code Playgroud)