c - Passing a HANDLE to a DLL -
i'm new win32 programming. i'm trying pass handle obtained using createfile() function in dll. upon trying read bytes, dwbytesread says 0. allowed pass handles dll entries? read here [writing dlls] resources of caller not belong callee, , hence should not call closehandle() or things free() malloc() in caller.
understanding correct? kindly point me in right direction. here's code:
main.c
#include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe.h> #define buffersize 5 int __declspec( dllimport ) hello( handle ); void __cdecl _tmain(int argc, tchar *argv[]) { handle hfile; printf("\n"); if( argc != 2 ) { printf("usage error: incorrect number of arguments\n\n"); _tprintf(text("usage:\n\t%s <text_file_name>\n"), argv[0]); return; } hfile = createfile(argv[1], // file open generic_read, // open reading file_share_read, // share reading null, // default security open_existing, // existing file file_attribute_normal | file_flag_overlapped, // normal file null); // no attr. template if (hfile == invalid_handle_value) { _tprintf(text("terminal failure: unable open file \"%s\" read.\n"), argv[1]); return; } printf( "entered main, calling dll.\n" ); hello(hfile); printf( "back in main, exiting.\n" ); closehandle(hfile); }
hello.c
#include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe.h> #define buffersize 5 dword g_bytestransferred = 0; void callback fileiocompletionroutine( __in dword dwerrorcode, __in dword dwnumberofbytestransfered, __in lpoverlapped lpoverlapped ) { _tprintf(text("error code:\t%x\n"), dwerrorcode); _tprintf(text("number of bytes:\t%x\n"), dwnumberofbytestransfered); g_bytestransferred = dwnumberofbytestransfered; } int __declspec( dllexport ) hello( handle hfile ) { dword dwbytesread = 0; char readbuffer[buffersize] = {0}; overlapped ol = {0}; if( false == readfileex(hfile, readbuffer, buffersize-1, &ol, fileiocompletionroutine) ) { dword lasterror = getlasterror(); printf("terminal failure: unable read file.\n getlasterror=%08x\n", lasterror); return lasterror; } dwbytesread = g_bytestransferred; if (dwbytesread > 0 && dwbytesread <= buffersize-1) { readbuffer[dwbytesread]='\0'; printf("data read file (%d bytes): \n", dwbytesread); printf("%s\n", readbuffer); } else if (dwbytesread == 0) { printf("no data read file \n"); } else { printf("\n ** unexpected value dwbytesread ** \n"); } printf( "hello dll!\n" ); return( 0 ); }
you missing sleepex(5000, true)
call example.
you using async-io, in case receive callback when read occurs. if don't wait callback may 0
bytes read depending on when callback triggered.
Comments
Post a Comment