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

Createfile works, but handle is invalid on FileStream Construction

我正在尝试通过 HID 连接到 Unity3D 中的 Wiimote。

当我调用CreateFile()(从kernel32)时返回一个"valid"指针,我什至可以通过HidD_GetPreparsedDataHidP_GetCaps获得Wiimote的能力。缓冲区大小等被返回,并且是我期望的大小。但是,当我尝试打开句柄上的 FileStream 时,出现 "Invalid Handle".

错误

如果我可以GetCaps,这个handle怎么会在这里无效呢? 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 构造函数中设置 useAsync = true(尽管在 Unity 中仍然 Invalid Handle

终于通过使用 kernel32.dll 的 ReadFile 方法让它工作了... 显然 Unity 在 SafeFileHandles 方面存在问题。:S 使用这个 API: http://buiba.blogspot.nl/2009/06/using-winapi-createfile-readfile.html 让阅读成为可能