2015-10-19 182 views
0

我試圖通過HID連接到Unity3D中的Wiimote。Createfile有效,但FileStream上的句柄無效構造

當我呼叫CreateFile()(來自kernel32)時,會返回一個「有效」指針,我甚至可以通過HidD_GetPreparsedDataHidP_GetCaps獲得Wiimote的功能。緩衝區大小等被返回,並且是我期望的大小。但是,當我嘗試在句柄上打開FileStream時,它出現「無效句柄」的錯誤。

如果我可以GetCaps,這個手柄如何無效? Marshal32.GetLastWinError()也返回0。

相關代碼:

int i = 0; 
foreach (string devPath in devicePaths) 
{ 
    Debug.Log(i); 
    i++; 
    if (devPath.Contains(VID_NINTENDO)) 
     if (devPath.Contains(PID_WIIMOTE)) // ADD OTHER PID (IF EVER FOUND) 
     { 
      try 
      { 
       IntPtr dev_Handle = CreateFile(devPath, FileAccess.Read | FileAccess.Write, FileShare.Read | FileShare.Write, IntPtr.Zero, FileMode.Open, FILE_FLAG_OVERLAPPED, IntPtr.Zero); // Gives a "Valid" pointer 
       IntPtr device_data = IntPtr.Zero; 
       int inputLength = 0; 
       try 
       { 
        if (!HidD_GetPreparsedData(dev_Handle, out device_data)) 
        { 
         throw new HIDException("Unable to get Preparsed data from device"); 
        } 
        HidCaps device_capabilities; // Struct to contain inputlength etc. 
        HidP_GetCaps(device_data, out device_capabilities); 
        inputLength = device_capabilities.InputReportByteLength; 
        int outputLength = device_capabilities.OutputReportByteLength; 
        FileStream stream = new FileStream(dev_Handle, FileAccess.Read | FileAccess.Write, true, inputLength); // INVALID HANDLE 
        //FileStream stream = new FileStream(new SafeFileHandle(dev_Handle, false), FileAccess.Read | FileAccess.Write, inputLength, true); // Invalid Handle 
        //FileStream stream = new FileStream(dev_Handle, FileAccess.Read | FileAccess.Write, true, inputLength); // Invalid Handle 
        //FileStream stream = new FileStream(devPath, FileMode.Open, FileAccess.Read | FileAccess.Write, FileShare.Read | FileShare.Write, inputLength); // nullref (The file isnt being created in this path) 
        Debug.Log(dev_Handle); 
       } 
       catch (Exception e) 
       { 
        HandleException(e, "HIDException"); 
       } 
       finally 
       { 
        HidD_FreePreparsedData(ref device_data); 
       } 
      } 
      catch (Exception e) 
      { 
       HandleException(e, "HIDException"); 
      } 
     }        
    } 

此外,在一個常規的C#項目它只是工作:((雖然我也必須設置在的FileStream構造函數(仍然Invalid Handle在useAsync =真統一雖然)

+0

請參閱[「應該問題包括」標籤「在他們的標題?」](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-標題),其中共識是「不,他們不應該」! –

回答