Struct size, check 64-bit or 32-bit

I have a Windows application that performs a simple procedure to determine if a USB token is present. The method always worked correctly on 32-bit machines, however, during testing on a 64-bit machine, we began to see unexpected results.

I call the following method

[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);

The documentation for the SP_DEVINFO_DATA structure tells us that cbSize is the size in bytes of the SP_DEVINFO_DATA structure.

If we calculate cbSize for a 32-bit machine, there will be 28 and 32 for a 64-bit machine.

I tested this on both machines, recompiling with different cbSize values, what I want to know is, how can I calculate this as the runtime? My application should work on both architectures.

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);
}

thank

Rohan

+3
4

Marshal.SizeOf:

_deviceInfoData = new Win32DeviceMgmt.SP_DEVINFO_DATA
    {
        cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA);
        // etc..
    }
+9

IntPtr 32 64

cbsize = IntPtr.Size == 4 ? 28 : 32

EDIT: IntPtr.Size, Hans System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA); , . , .

+1

Environment.Is64BitOperatingSystem Environment.Is64BitProcess.

+1

.

Pack.

: http://www.pinvoke.net/default.aspx/Structures/SP_DEVINFO_DATA.html

:

32- SetupApi 1 . 64- SetupApi 8- . IE 32 SP_DEVINFO_DATA.cbSize = 28, 64 SP_DEVINFO_DATA.cbSize = (28 + 4) = 32.SP_DEVINFO_DATA.cbSize = (28 + 4) = 32.

0

Source: https://habr.com/ru/post/1765737/


All Articles