我正在尝试通过HID连接到Unity3D中的Wiimote。
当我调用CreateFile()
(来自kernel32)时,返回一个"有效"的指针,我甚至可以通过HidD_GetPreparsedData
和HidP_GetCaps
获得Wiimote的功能。Buffer-size等返回,是我期望的大小。但是,当我试图在句柄上打开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构造函数中设置useAsync = true(尽管在Unity中仍然是Invalid Handle
)
最后通过使用kernel32.dll
的ReadFile方法使其工作…显然Unity有SafeFileHandles的问题…:年代使用此API:http://buiba.blogspot.nl/2009/06/using-winapi-createfile-readfile.html使阅读成为可能