internal static extern unsafe bool SetupDiEnumDeviceInterfaces( DeviceInformationSetHandle DeviceInfoSet, IntPtr DeviceInfoData, ref Guid InterfaceClassGuid, UInt32 MemberIndex, ref DeviceInterface.Native DeviceInterfaceData );
internal static extern unsafe bool SetupDiGetDeviceInterfaceDetailW( DeviceInformationSetHandle DeviceInfoSet, ref DeviceInterface.Native DeviceInterfaceData, byte *DeviceInterfaceDetailData, UInt32 DeviceInterfaceDetailDataSize, ref UInt32 RequiredSize, IntPtr DeviceInfoData );
private unsafe bool TryGetInterface(uint interfaceIndex, out DeviceInterface?ret) { DeviceInterface.Native native = new DeviceInterface.Native(); native.cdSize = (uint)Marshal.SizeOf(typeof(DeviceInterface.Native)); try { bool success = SetupDiEnumDeviceInterfaces( handle, IntPtr.Zero, ref guid, interfaceIndex, ref native ); if (!success) { throw new Win32Exception(); } } catch (Win32Exception err) when(err.NativeErrorCode == ERROR_NO_MORE_ITEMS) { ret = null; return(false); } { bool success; UInt32 requiredSize = 0; try { success = SetupDiGetDeviceInterfaceDetailW( handle, ref native, null, 0, ref requiredSize, IntPtr.Zero ); if (!success) { throw new Win32Exception(); } } catch (Win32Exception err) when(err.NativeErrorCode == ERROR_INSUFFICIENT_BUFFER) { } byte[] buffer = new byte[requiredSize]; int varPartOffset = (int)Marshal.OffsetOf(typeof(DeviceInterface.DetailsNative), "data"); int structSize = Marshal.SizeOf(typeof(DeviceInterface.DetailsNative)); fixed(byte *bufferP = buffer) { *(UInt32 *)bufferP = (uint)structSize; success = SetupDiGetDeviceInterfaceDetailW( handle, ref native, bufferP, requiredSize, ref requiredSize, IntPtr.Zero ); if (!success) { throw new Win32Exception(); } char * stringPtr = (char *)(bufferP + varPartOffset); string filePath = new string(stringPtr); ret = native.AsManaged(filePath); return(true); } } }