Asynchronous windows I/O ( Overlapped I/O ) (continue)

>> Sunday, October 18, 2009

In part 1, i described functions and how to use the asynchronous I/O operations.
Now it's time to go more deeply in these operations

The thing i want to show here is the CALLBACK function for the completion of overlapped I/O operations.
At first, let's see the codes sample:

#include <windows.h>
#include <iostream>
using namespace std;

VOID CALLBACK completion_routine(DWORD error_code, DWORD
number_bytes_transferred, LPOVERLAPPED lovl)
{
  cout << "ErrorCode: " << error_code << endl << 
"\tNumber of bytes transferred: " << number_bytes_transferred << endl << 
"\t Offsets: " << (*lovl).OffsetHigh << ' ' << (*lovl).Offset << endl;
}

int main()
{
  HANDLE hFile;
  OVERLAPPED ovl = 
{
    0, 0, 0, 0, 0
  };
  hFile = CreateFile("C:\demo.dat", GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
    OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);
  // write to file
  for (int i = 0; i < 10; ++i)
  {
    WriteFileEx(hFile, &i, sizeof(i), &ovl, completion_routine);
    SleepEx(INFINITE, TRUE);
    ovl.Offset += sizeof(i);
  }
  CloseHandle(hFile);
  return 0;
}



Firstly is the prototype of callback function:


VOID CALLBACK procedure_name(DWORD error_code, DWORD number_of_byte_transferred, LPOVERLAPPED lovl);

The parameters are self-explained.
Secondly, we use the function WriteFileEx with prototype:


BOOL WriteFileEx(HANDLE hFile, LPCVOID lpBuffer, DWORD number_of_bytes_to_write, LPOVERLAPPED lovl, LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);

Remark the LPOVERLAPPED_COMPLETION_ROUTINE here, it's the type of callback function we described above.

0 comments: