使用PInvoke在.NET中进行WinUSB异步调用

时间:2013-04-19 02:57:01

标签: .net callback pinvoke winusb

我已经使用USB对微控制器进行了编程,并使用WinUSB将其连接到PC。我可以使用带有同步(阻塞,重叠= NULL)调用的pinvoke在c ++和VB.NET中与我的uC进行通信。我刚刚使用c ++进行异步调用,但我不知道如何在.NET中编写它,还有另外一个我不确定的问题:

问题1: 在c ++中,我最初尝试使用IO完成回调对象进行异步调用,但是当我调用WinUSB来读取它时,返回错误,异步IO已经在文件句柄上进行(HANDLE hDevice),CreateThreadpoolIo不会采用WinUSB句柄(PWINUSB_INTERFACE_HANDLE hWinUsbHandle) 。我的猜测是WinUSB使用IO的这个文件句柄,所以我不能。我最终使用Wait Callback Objects进行了工作。它现在正在运作,我只是想澄清我正在做的是正确的用法。

我有点困惑的部分是CreateThreadpoolWait调用。起初我以为这是像MSDN中的其他示例一样创建一个线程池,但我认为现在它只是一个在默认线程池上运行的对象。此外,objConext是用于将调用与其回调同步的变量,即回调中的PVOID Context指向objConext。

以下是c代码段:

// Receive data asynchronously
void BeginReceiveData(UCHAR bytPipeId, UCHAR *bytData, ULONG intLength, PTP_WAIT_CALLBACK cbCallback)
{
    // Create the event
    HANDLE hEventCallback = CreateEvent(NULL, FALSE, FALSE, NULL);

    // Check for an error
    if (!hEventCallback)
    {
        // Set the error
        printf(strError, "Error creating callback event: %d.", GetLastError());
    }

    // Create the thread pool wait object
    tpWait = CreateThreadpoolWait(cbCallback, &objConext, NULL);

    // Check for an error
    if (!tpWait)
    {
        // Set the error
        printf(strError, "Error creating thread pool: %d.", GetLastError());
    }

    // Place the wait object in the thread pool
    SetThreadpoolWait(tpWait, hEventCallback, NULL);

    // Clear the callback
    ZeroMemory(&oCallback, sizeof(oCallback));

    // Set the event
    oCallback.hEvent = hEventCallback;

    // Read
    BOOL bResult = WinUsb_ReadPipe(*hWinUsbHandle, bytPipeId, bytData, intLength, NULL, &oCallback);

    // Check for an error
    if (!bResult)
    {
        if (GetLastError() != ERROR_IO_PENDING)
        {
            // Set the error
            printf(strError, "Error reading pipe: %d.", GetLastError());
        }
    }
}

// Receive data callback
void CALLBACK UsbCallback(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WAIT Wait, TP_WAIT_RESULT WaitResult)
{
}

问题2: 如何将上面的内容转换为.NET?这是我到目前为止的猜测:

    Dim wait As New WaitCallback(AddressOf UsbCallback)

    ' Create the event
    Dim eEventCallback As New AutoResetEvent(False)

    ThreadPool.QueueUserWorkItem(wait, Nothing)

    Dim oCallback As New Overlapped(0, 0, eEventCallback.SafeWaitHandle.DangerousGetHandle, Nothing)

    'Dim oCallback As New NativeOverlapped

    oCallback.EventHandleIntPtr = eEventCallback.SafeWaitHandle.DangerousGetHandle

    ' Read
    Dim bResult As Boolean = WinUsb_ReadPipe(hWinUsbHandle, bytPipeId, bytData, intLength, intLength, oCallback.EventHandleIntPtr)

<DllImport("winusb.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
        Public Function WinUsb_ReadPipe(InterfaceHandle As IntPtr, PipeID As Byte, Buffer() As Byte, BufferLength As UInteger, ByRef LengthTransferred As UInteger, Overlapped As IntPtr) As Boolean
        End Function

编辑:我打算发帖作为答案,但我没有足够的街头信誉

好吧,我有点将代码转换为.NET的答案。我设法将所有API函数转换为PInvoke,然后替换除了一对之外构建到.NET中的函数。代码有效,但必须注意声明变量的位置,因为GC会在回调之前清理它们。此外,必须仔细分配和销毁上下文。例如,如果没有分配正确大小的内存,则可以清理上下文结构中的数组,这很容易理解。

由于这些原因,为USB中的每个管道保留对象中的句柄引用并重用它们可能更有利,因为在前一个管道完成之前无法对同一个管道进行多次调用。如果这样做,那么您可以对上下文执行相同操作,并避免为上下文分配和销毁内存。例如,可以在回调中的Wait指针上使用字典:

Dim dicHandlesAndContext As Dictionary(Of IntPtr, HandlesAndContext)

虽然我还没有真正找到问题1的答案:这是否是“正确”的方法,但它似乎表现得相当不错。以下是主要代码片段:

' Receive data asynchronously
    Private Sub BeginReceiveData(bytPipeId As Byte, bytData() As Byte, intLength As UInteger)
        ' Allocate memory for the callback
        ptrContext = Marshal.AllocHGlobal(Marshal.SizeOf(GetType(TestContext)))

        ' Copy the structure to memory
        Marshal.StructureToPtr(objConext, ptrContext, True)


        ' Create the callback
        cbCallback = New UsbCallbackDelegate(AddressOf UsbCallback)


        ' Create the event
        Dim areEvent As New AutoResetEvent(False)

        ' Set the event
        hEventCallback = areEvent.SafeWaitHandle.DangerousGetHandle

        ' Create the thread pool wait object
        tpWait = CreateThreadpoolWait(Marshal.GetFunctionPointerForDelegate(cbCallback), ptrContext, IntPtr.Zero)

        ' Place the wait object in the thread pool
        SetThreadpoolWait(tpWait, hEventCallback, IntPtr.Zero)

        ' Set the event
        oCallback.EventHandle = hEventCallback

        ' Read
        Dim bResult As Boolean = WinUsb_ReadPipe(hWinUsbHandle, bytPipeId, bytData, intLength, intLength, oCallback)

        If Not bResult Then
            If Not Marshal.GetLastWin32Error = 997 Then
                ' Get the error
                Dim intError As Integer = Marshal.GetLastWin32Error

                Throw New Win32Exception(intError, "Error getting device information.")
            End If
        End If
    End Sub

    ' Delegate for USB callbacks
    Private Delegate Sub UsbCallbackDelegate(Instance As IntPtr, Context As IntPtr, Wait As IntPtr, WaitResult As UInteger)

    ' Callback
    Private Sub UsbCallback(Instance As IntPtr, Context As IntPtr, Wait As IntPtr, WaitResult As UInteger)
        ' Number of bytes transferred
        Dim intTransferred As UInteger

        ' Get the number of bytes transferred
        WinUsb_GetOverlappedResult(hWinUsbHandle, oCallback, intTransferred, False)

        ' Get the context from memory
        Dim objConext As TestContext = Marshal.PtrToStructure(Context, GetType(TestContext))

        ' Free the memory
        Marshal.FreeHGlobal(Context)


        ' Do some work on the data


End Sub

主API DLL导入

<DllImport("winusb.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
        Public Function WinUsb_GetOverlappedResult(InterfaceHandle As IntPtr, ByRef lpOverlapped As Threading.NativeOverlapped, ByRef lpNumberOfBytesTransferred As UInteger, bWait As Boolean) As IntPtr
        End Function

        <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
        Public Function CreateThreadpoolWait(pfnwa As IntPtr, pv As IntPtr, pcbe As IntPtr) As IntPtr
        End Function

        <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
        Public Function SetThreadpoolWait(pwa As IntPtr, h As IntPtr, pftTimeout As IntPtr) As IntPtr
        End Function

        <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
        Public Function CloseThreadpoolWait(pwa As IntPtr) As IntPtr
        End Function

我通过连续接收数据并同时运行GC来测试这些GC保护功能,如果收集了某些内容,程序将会崩溃。

' Receive data asynchronously on endpoint 1
    BeginReceiveData(129, bytData, 8)

    While True
    ' Garbage collection
        GC.Collect()
        GC.WaitForFullGCComplete()
    End While


    ' Callback
    Private Sub UsbCallback(Instance As IntPtr, Context As IntPtr, Wait As IntPtr, WaitResult As UInteger)
        ' ...
        ' Once data is received, receive more
        BeginReceiveData(129, bytData, 8)
        '...
    End Sub

警告:此处没有大量清理代码,请查看MSDN以获取有关如何正确执行此操作的c代码。我认为面向对象的方法可能最好保持句柄处于活动状态,并在完成后实现IDIsposable清理。

对开源DLL感兴趣的人? :P

0 个答案:

没有答案