问题描述
我正在尝试开发一种与电子卡通信的功能.我需要使用readFile()函数:
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);
我的功能是:
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
最后一行中的函数Marshal.GetLastWin32Error()
返回错误代码997.
The function Marshal.GetLastWin32Error()
in the last line returns error code 997.
在第二段中,出现另一个错误,代码为0xc0000005(FatalExecutionEngineError),并且软件崩溃.
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?
推荐答案
这不是问题.
错误代码997是ERROR_IO_PENDING
,这是ReadFile
在开始重叠读取时将返回的内容.
Error code 997 is ERROR_IO_PENDING
, which is what ReadFile
will return upon starting an overlapped read.
从文档:
备注:
使用重叠的I/O是一项要求吗?
Is using overlapped I/O a requirement?
使用此函数定义:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
您可以从使用Win API打开的文件中创建常规的FileStream
:
You can create regular FileStream
s from a file opened with the Win API:
var fileHandle = CreateFile(.....);
if (fileHandle.IsInvalid)
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
// The last parameter of the FileStream constructor (isAsync) will make the class use async I/O
using (var stream = new FileStream(fileHandle, FileAccess.ReadWrite, 4096, true))
{
var buffer = new byte[4096];
// Asynchronously read 4kb
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
}
这篇关于pInvoke readFile():重叠的I/O操作正在进行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!