473,387 Members | 1,904 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 13933
>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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...

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.