Createfile有效,但FileStream上的句柄无效构造

问题描述:

我试图通过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-标题),其*识是“不,他们不应该”! –

终于得到它通过使用kernel32.dll的ReadFile的方法工作... 显然团结与SafeFileHandles问题..:S 使用这个API: http://buiba.blogspot.nl/2009/06/using-winapi-createfile-readfile.html 使阅读成为可能