2

I want to read some data from a device connected to a COM port.

  • HANDLE handle =CreateFileW(L"\\\\.\\COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

    gives me a valid HANDLE which is then configured via GetCommState and SetCommState.

  • OVERLAPPED ol = {0};

    char buffer[1024];

    ol.Offset = 0;

    ol.OffsetHigh = 0;

    ReadFileEx(handle, buffer, 1, &ol, NULL);

    The problem is, that this call doesn't succeed and GetLastError() returns 87 (ERROR_INVALID_PARAMETER).

What could I try to be able to read from the device?

Etan
  • 17,014
  • 17
  • 89
  • 148

2 Answers2

1

The ReadFileEx documentation states that

The ReadFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that member for its own purposes in the context of a ReadFileEx call. ReadFileEx signals completion of its read operation by calling, or queuing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an event handle.

So although it also says that the completion routine is optional, it's probably needed. Also note the community comment at the bottom of the page you linked to - MS may have fixed that crash by considering a NULL lpCompletionRoutine an error. However, I have not tested it to verify.

If you are not using a completion routine you can use the normal ReadFile for your overlapped operation.

tinman
  • 6,348
  • 1
  • 30
  • 43
1

There is also a bug in MS implementation of ReadFileEx. Despite the documentation clearly stating that one should not reply entirely on the BOOL return result and that one should also check GetLastError() the implementation fails to clear any pre-existing error. Add a SetLastError(ERROR_SUCCESS) before calling ReadFileEx().

Elmo
  • 6,409
  • 16
  • 72
  • 140
Jay
  • 11
  • 1