gpt4 book ai didi

c++ - WIN API ReadFile() 返回 GetLastError() ERROR_INVALID_PARAMETER

转载 作者:太空狗 更新时间:2023-10-29 20:58:10 24 4
gpt4 key购买 nike

我在下面编写了这段代码,它在 code::blocks 下运行良好,使用 mingw gcc 4.7 进行编译。从那以后,我决定开始使用 Visual Studio 2013 Express。现在调用 ReadFile() 时出现错误。这似乎是一个无效参数。我看不到错误,希望这里有人能发现它。

这一切都包含在一个类 Serial 中。从我在 IDE 中看到的情况来看,与 CreateFile() 返回句柄的引用相比,m_hSerial 的内存引用是正确的。

m_hSerial = CreateFile(m_pchPort,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);

我这样调用WorkThread

m_hThread = (HANDLE)_beginthreadex(0, 0, &WorkThread, (void*) this, 0, 0);

这是工作线程代码

unsigned int __stdcall Serial::WorkThread(void* pvParam)
{
// This is a pointer to the 'this' serial class.
// Needed to be able to set members of the class in a static class function
Serial * cThis = (Serial*) pvParam;
// Set up the overlapped event
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
ov.hEvent = CreateEvent(0, true, 0, 0);
DWORD dwEventMask = 0;
DWORD dwWait;
HANDLE aHandles[2];
aHandles[0] = cThis->m_hThreadTerminator;
aHandles[1] = ov.hEvent;

SetEvent(cThis->m_hThreadRunning);
while (true)
{
if (!WaitCommEvent(cThis->m_hSerial, &dwEventMask, &ov))
{
assert(GetLastError() == ERROR_IO_PENDING);

}

dwWait = WaitForMultipleObjects(2, aHandles, FALSE, INFINITE);
switch(dwWait)
{
case WAIT_OBJECT_0:
{
_endthreadex(1);
}
case WAIT_OBJECT_0 + 1:
{
if (dwEventMask & EV_TXEMPTY)
{
ResetEvent(ov.hEvent);
}
else if (dwEventMask & EV_RXCHAR)
{
// read data here
DWORD dwBytesRead = 0;
DWORD dwErrors;
COMSTAT cStat;
OVERLAPPED ovRead;
ovRead.hEvent = CreateEvent(0, true, 0, 0);

// Get the Bytes in queue
ClearCommError(cThis->m_hSerial, &dwErrors, &cStat);
DWORD nSize = cStat.cbInQue;
// EM_REPLACESEL needs a LPARAM null terminated string, make room and set the CString NULL
char *szBuf = new char[nSize+1];
memset(szBuf, 0x00, sizeof(szBuf));

if (!ReadFile(cThis->m_hSerial, &szBuf, nSize, &dwBytesRead, &ovRead))
DWORD err = GetLastError();
if (dwBytesRead == nSize)
SendMessage(cThis->m_hHwnd, WM_SERIAL, 0, LPARAM(&szBuf));

CloseHandle(ovRead.hEvent); // clean up!!!
delete[] szBuf;
}
// Reset the overlapped event
ResetEvent(ov.hEvent);
}
break;
}//switch
}

return 0;

最佳答案

ReadFile(cThis->m_hSerial, &szBuf, nSize, &dwBytesRead, &ovRead)

你要求一个异步操作,同时要求函数告诉你已经读取了多少字节。您传递了 &dwBytesRead 作为倒数第二个参数。当您执行重叠读取时,为此参数传递 NULLdocumentation说:

Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.

在上面的代码中传递&szBuf也是错误的。你的意思是传递 szBuf

您也无法初始化 OVERLAPPED 结构。这样做:

OVERLAPPED ovRead = {};

一个更大的问题是您请求异步访问,但随后编写的代码就像它是同步的一样。 ReadFile 返回后,您将尝试从 dwBytesRead 中获取有意义的信息,并关闭放置在重叠结构中的事件。

如果您真的打算异步编写代码,则需要重新编写异步代码。从表面上看,您似乎还没有完全理解重叠 I/O 的含义,您或许应该切换到非重叠、同步 I/O。

关于c++ - WIN API ReadFile() 返回 GetLastError() ERROR_INVALID_PARAMETER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com