473,473 Members | 1,535 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

ReadFile OVERLAPPED

I am trying to do an Overlapped ReadFile on a HID device and it just isn't
working for me. The WaitForSingleObject keeps giving me an error "The
system cannot find the file specified."

This code need to work in 64bit and 32bit, so I am using IntPtr for pointers
instead of int.

Here is the structure of OVERLAPPED
[StructLayout(LayoutKind.Sequential)]
public struct OVERLAPPED
{
public IntPtr Internal;
public IntPtr InternalHigh;
public int Offset;
public int OffsetHigh;
public IntPtr hEvent;
}

Here is how I setup the event:

IntPtr eventObject = FileIOAPIDeclarations.CreateEvent( IntPtr.Zero,
System.Convert.ToInt32(false), System.Convert.ToInt32(false), "");

Here is the declaration of the CreateEvent:
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static public extern IntPtr CreateEvent(IntPtr SecurityAttributes, int
bManualReset, int bInitialState, string lpName);

I set the OVERLAPPED.Offset and OffsetHigh = 0, and then I set hEvent =
eventObject.

I then call my ReadFile

fixed (byte* p = buffer)
{
result = FileIOAPIDeclarations.ReadFile(_hidHandle, p, buffer.Length,
&bytesRead, ref HIDOverlapped);
Debug.WriteLine(MyDebugging.ResultOfAPICall("ReadF ile"));
}

The decliration for the ReadFile is this:

[DllImport("kernel32.dll", SetLastError = true)]
static public extern unsafe int ReadFile(IntPtr hFile, void* lpBuffer, int
nNumberOfBytesToRead, int* lpNumberOfBytesRead, ref
FileIOAPIDeclarations.OVERLAPPED lpOverlapped);
This ReadFile declaration and call is required for 64 bit to work correctly.

After I call the ReadFile I do get a message from the GetLastError() that
"Overlapped I/O operation is in process."

Then I call the WaitForSingleObject

result = FileIOAPIDeclarations.WaitForSingleObject(HIDOverl apped.hEvent,
3000);

WaitForSingleObject declaration

[DllImport("kernel32.dll", SetLastError = true)]
static public extern int WaitForSingleObject(IntPtr hHandle, int
dwMilliseconds);

After 3 seconds this always returns timeout (0x102, 258) and the
GetLastError() is: "The system cannot find the file specified."

To me this is telling me that one of my structures is off, but I am not sure
which one.

Thanks in advance for any help.

Eric Renken


Jun 21 '07 #1
4 13950
>Here is the declaration of the CreateEvent:
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static public extern IntPtr CreateEvent(IntPtr SecurityAttributes, int
bManualReset, int bInitialState, string lpName);
FYI you can use bool for the boolean parameters, so you don't have to
use Convert.ToInt32.

>
I set the OVERLAPPED.Offset and OffsetHigh = 0, and then I set hEvent =
eventObject.

I then call my ReadFile

fixed (byte* p = buffer)
{
result = FileIOAPIDeclarations.ReadFile(_hidHandle, p, buffer.Length,
&bytesRead, ref HIDOverlapped);
Debug.WriteLine(MyDebugging.ResultOfAPICall("ReadF ile"));
}
Not sure if this is what's causing your problem. But the p pointer is
only valid inside the fixed block. It's not suitable for asynch
procedure calls. You have to make sure you pass a pointer that's valid
until you've finished reading. You can do that by either manually
pinning the array or allocating a buffer from a native heap.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Jun 21 '07 #2
I agree with Mattias here. Eric, you should be able to use GCHandle to pin
the buffer or use Marshal.AllocHGlobal.

Let us know if this helps.
Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 22 '07 #3
Well this code works:

GCHandle gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
result = FileIOAPIDeclarations.ReadFile(_hidHandle,
gch.AddrOfPinnedObject(), buffer.Length, &bytesRead, ref HIDOverlapped);

if (result != 0)
success = true;

result = FileIOAPIDeclarations.WaitForSingleObject(HIDOverl apped.hEvent,
500);

gch.Free();

_readHandle = IntPtr.Zero;

switch (result)
{
case FileIOAPIDeclarations.WAIT_OBJECT_0:
success = true;
break;

case FileIOAPIDeclarations.WAIT_TIMEOUT:
success = false;
break;
}
Thank you all, the really strange thing is that our device that you do a
Write and an immediate Read to doesn't work with this code. I still get a
Time-out Error. With a new device we are working on this code works great;
however I am finding that I need to close and then reopen the connection for
every read/time-out. I am working in a loop here, so I keep monitoring this
device for data, if someone has a better way that would also be great,
anyway I find that if I call the read again after the time-out and then I
put data on the device I have to wait until that data is put onto the device
there for as many times as the time-out occurred.

What I am saying is that if the Read timed-out 5 times, I have to put data
on the device 6 times before the Read returns any data.

Thanks again,

Eric Renken

"Walter Wang [MSFT]" <wa****@online.microsoft.comwrote in message
news:Ig**************@TK2MSFTNGHUB02.phx.gbl...
>I agree with Mattias here. Eric, you should be able to use GCHandle to pin
the buffer or use Marshal.AllocHGlobal.

Let us know if this helps.
Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no
rights.

Jun 22 '07 #4
Hi Eric,

Thanks for the update.

I was just informed by Jeffrey Richter that he has a new article on MSDN
Magazine about asynchronous device I/O in managed code:

#Concurrent Affairs: Asynchronous Device Operations -- MSDN Magazine, June
2007
http://msdn.microsoft.com/msdnmag/is...urrentAffairs/
I think this should be useful for you.
Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 25 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Mustafa Ahmad Malik | last post by:
Hello, I have wrapped the Win32 pipes function in C#. I have created named pipe with PIPE_WAIT in pipemode parameter like this pipehandle = CreateNamedPipe(_pipeName, PIPE_ACCESS_DUPLEX,...
12
by: ORC | last post by:
Shouldn't 'ReadFile' block when timeouts are specified even when running in overlapped mode or am I wrong ??? Thanks Ole
3
by: Shawn August | last post by:
Hello: I am converting a working VB6 program to C#. During testing of the C# version, I noticed the ReadFile API is crashing. The parameters going into the this function are identical to the...
2
by: GTi | last post by:
StringBuilder text = new StringBuilder(lpNextSize+1, lpNextSize+1); int pNumberOfBytesRead = text.Capacity; try { result=win32.ReadFile(_Handle, text, text.Capacity, ref pNumberOfBytesRead, 0); }...
2
by: CeZaR | last post by:
Hi, What does the "overlapped" word means in windows programming? I've read about overlapped structures, functions?! What does it mean? Thanks!
2
by: Schorschi | last post by:
Can't seemd to get ReadFile API to work! Returns invalid handle error? =========================================================================== Ok, the visual basic gurus, help! The...
1
by: dvestal | last post by:
I'm trying to use Overlapped I/O from C#, and utterly failing. I've tried to boil down my code to as simple an example as possible, in hopes that you people can point to where I'm going wrong. ...
15
by: Ketchup | last post by:
Hello everyone, I have been stuck with this problem for quite some time now. I am working in VB.NET, using framework 1.0. I have to keep the compatibility down to the original .NET framework...
7
by: =?Utf-8?B?TmljayBCdXJraXR0?= | last post by:
Hi. I have a C# app that uses named pipes via InteropServices. I have no problems running on a 32-bit machine, or when targeting x86 architecture, but it fails on a 64-bit machine when...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.