I'm trying to develop a function to communicate with an electronic card. I need to use the readFile() function :
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadFile(IntPtr hFile, ref byte lpBuffer,
uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, Overlapped lpOverlapped);
My function is :
EventObject = CreateEvent(IntPtr.Zero,true,true,"");
lastError = Marshal.GetLastWin32Error();
HIDOverlapped = new System.Threading.Overlapped();
HIDOverlapped.OffsetLow = 0;
HIDOverlapped.OffsetHigh = 0;
HIDOverlapped.EventHandleIntPtr = EventObject;
readHandle = CreateFile(MyDeviceInterfaceDetailData.DevicePath, (GENERIC_READ | GENERIC_WRITE), (FILE_SHARE_READ | FILE_SHARE_WRITE), IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
uint numberOfBytesRead;
readBuffer= new byte[8];
string byteValue;
bool result = ReadFile(readHandle, ref readBuffer[0], (uint)capabilities.InputReportByteLength, out numberOfBytesRead, HIDOverlapped);
lastError = Marshal.GetLastWin32Error(); //Problem
The function Marshal.GetLastWin32Error()
in the last line returns error code 997.
In the sencond passage, an other error appears with the code 0xc0000005 (FatalExecutionEngineError) and the software crash.
Have you got an idea of what I can tried?
Straight from MSDN:
If you read the linked page, you will find that if you pass anything but
null
as the lpOverlapped parameter it will be an asynchronous call, so most likely your problem comes from the fact, that you try to use thereadBuffer
before it is set by the function - or in other words: before the read completes.And as Lucas already indicated in his answer, last error will return 997 while the operation is in progress, so this is the desired output.
This is not a problem.
Error code 997 is
ERROR_IO_PENDING
, which is whatReadFile
will return upon starting an overlapped read.From the docs:
Remarks:
Is using overlapped I/O a requirement?
How to use overlapped I/O from C# easily?
Using this function definition:
You can create regular
FileStream
s from a file opened with the Win API: