gpt4 book ai didi

c# - pInvoke readFile() : Overlapped I/O operation is in progress

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

我正在尝试开发一种与电子卡通信的功能。我需要使用 readFile() 函数:

[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。

在第二段中,出现另一个错误,代码为 0xc0000005 (FatalExecutionEngineError),软件崩溃。

你知道我可以尝试什么吗?

最佳答案

不是问题。

错误代码 997 是 ERROR_IO_PENDING,这是 ReadFile 在开始重叠读取时将返回的内容。

来自docs :

Note The GetLastError code ERROR_IO_PENDING is not a failure; it designates the read operation is pending completion asynchronously. For more information, see Remarks.

备注:

ReadFile may return before the read operation is complete. In this scenario, ReadFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING, which allows the calling process to continue while the system completes the read operation.

使用重叠 I/O 是一项要求吗?


如何在 C# 中轻松使用重叠 I/O?

使用这个函数定义:

[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:

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);
}

关于c# - pInvoke readFile() : Overlapped I/O operation is in progress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24552548/

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