作为 WSARecvFrom 调用的一部分,如何将缓冲区放入 CompletionROUTINE?

How to get buffer into CompletionROUTINE as apart of WSARecvFrom call?

我在 UDP 服务器上工作,并尝试使用重叠 IO。我一直在尝试使用 MSDN 示例和文档进行研究,但没有找到使用函数的 lpCompletionRoutine 参数。

我注意到您将 PWSAOVERLAPPED 传递给 WSARecvFrom,它包含一个 LPVOID Pointer 成员。我是否会创建自己的用户数据结构,其中包含对缓冲区的引用并将其作为指针传递到 PWSAOVERLAPPEDPointer 成员中?

虽然收到的字节在两个地方可用,但我认为这有点多余:

WSARecvFromlpNumberOfBytesRecvd 参数,以及 lpCompletionRoutinecbTransferred 参数。

我当前的完成例程示例:

void CALLBACK CompletionROUTINE(
  DWORD dwError, 
  DWORD cbTransferred, 
  LPWSAOVERLAPPED lpOverlapped, 
  DWORD dwFlags
) {
    UNREFERENCED_PARAMETER(dwError);
    UNREFERENCED_PARAMETER(lpOverlapped);
    UNREFERENCED_PARAMETER(dwFlags);

    /* Best way to get the bytes read here? */
    Printf(L"Recieved %d bytes\n", cbTransferred);
}

和我给 WSARecvFrom 的电话:

iResult = WSARecvFrom(
    listenSocket, 
    &wsaBuffer, 
    1, 
    &dwBytesRecieved, 
    &dwFlags, 
    (PSOCKADDR)&sender, 
    &senderAddrSize, 
    &wsaOverlapped,
    CompletionROUTINE
);

来自WSAOVERLAPPED结构documentation:

hEvent Type: HANDLE If an overlapped I/O operation is issued without an I/O completion routine (the operation's lpCompletionRoutine parameter is set to null), then this parameter should either contain a valid handle to a WSAEVENT object or be null. If the lpCompletionRoutine parameter of the call is non-null then applications are free to use this parameter as necessary.

因为我提供了一个 lpCompletionRoutine 参数,所以我可以使用 WSAEvent 作为指向我的用户定义数据的指针。

感谢引导我得出这一发现的评论者。