我正在嘗試連接到USB GPS設備。如果我通過CreateFile WinApi手動創建文件(使用設備管理器中指定的路徑),我可以成功連接到設備。Win32Api USB SetupDiGetDeviceInterfaceDetail失敗
但是,當我嘗試通過枚舉選擇設備時,失敗@ SetupDiGetDeviceInterfaceDetail調用。
我有正確工作的C代碼,但我的C#翻譯似乎無法正常工作。我嘗試了許多基本相同的結果。
的作品// Get enumerator handle for the specified ClassGuid
HDEVINFO theDevInfo = SetupDiGetClassDevs((GUID*)&GUID_DEVINTERFACE_GRMNUSB, NULL, NULL,
DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
SP_DEVICE_INTERFACE_DATA theInterfaceData;
theInterfaceData.cbSize = sizeof(theInterfaceData);
// populate theInterfaceData which contains device class information
if (!SetupDiEnumDeviceInterfaces(theDevInfo, NULL, (GUID*)&GUID_DEVINTERFACE_GRMNUSB, 0, &theInterfaceData) &&
GetLastError() == ERROR_NO_MORE_ITEMS)
{
gHandle = 0;
return;
}
// This is normally used to obtain the device path information using theInterfaceData obtained above
bool initialized = SetupDiGetDeviceInterfaceDetail(theDevInfo, &theInterfaceData, NULL, 0, &theBytesReturned, NULL);
// theBytesReturned = 83
theDevDetailData =
(PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(theBytesReturned);
theDevDetailData->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
bool initialized = SetupDiGetDeviceInterfaceDetail(theDevInfo, &theInterfaceData, theDevDetailData, theBytesReturned, NULL, &theDevInfoData);
C代碼C#
[DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Boolean SetupDiGetDeviceInterfaceDetail(
IntPtr hDevInfo,
ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
IntPtr deviceInterfaceDetailData,
UInt32 deviceInterfaceDetailDataSize,
out UInt32 requiredSize,
IntPtr deviceInfoData
);
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVICE_INTERFACE_DATA
{
public Int32 cbSize;
public Guid interfaceClassGuid;
public Int32 flags;
private UIntPtr reserved;
}
// Get enumerator handle for the specified ClassGuid
IntPtr theDevInfo = SetupDiGetClassDevs(ref ClassGuid, (DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE));
SP_DEVICE_INTERFACE_DATA DevInterfaceData = new SP_DEVICE_INTERFACE_DATA();
DevInterfaceData.cbSize = Marshal.SizeOf(DevInterfaceData);
initialized = SetupDiEnumDeviceInterfaces(theDevInfo, IntPtr.Zero, ref ClassGuid, 0,
ref DevInterfaceData);
// I assume The DevInterfaceData is populated correctly as it matches the C Code
// And I've compared the values in memory and they match
uint bytesReturned = 0;
initialized = SetupDiGetDeviceInterfaceDetail(theDevInfo, ref DevInterfaceData, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);
// I expect bytesReturned = 83 and initialized = true which is the value that is returned in the C Code
// Instead the value 162 is returned
不,這會破壞堆棧。使用Marshal.AllocHGlobal()來分配具有所需大小的緩衝區。你從第一個電話獲得的大小。 – 2012-02-12 08:25:38
爲什麼/如何損壞堆棧?當我進行Win32api調用時,是不是應該封送適當的內存? – galford13x 2012-02-12 09:43:46
@HansPassant你有可能解釋爲什麼'IntPtr.Size'測試是必要的,我們不能依靠編組器來獲得'SizeOf(SP_DEVICE_INTERFACE_DETAIL_DATA)'對嗎?我猜它與填充有關嗎? – 2014-06-21 17:25:59