Home Ask Login Register

Developers Planet

Your answer is one click away!

user2338150 February 2016

Passing a HANDLE to a DLL

I'm new to Win32 programming. I'm trying to pass a HANDLE obtained using CreateFile() to a function in a DLL. But upon trying to read bytes, dwBytesRead says 0. Am I allowed to pass HANDLEs to DLL entries? I read here [Writing DLLs] that resources of the caller do not belong to callee, and hence I should not call CloseHandle() or things like free() for malloc() in caller.
Is my understanding correct? Kindly point me in the right direction. Here's the code:


#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; 

    if( argc != 2 )
        printf("Usage Error: Incorrect number of arguments\n\n");
        _tprintf(TEXT("Usage:\n\t%s <text_file_name>\n"), argv[0]);

    hFile = CreateFile(argv[1],               // file to open
                       GENERIC_READ,          // open for reading
                       FILE_SHARE_READ,       // share for reading
                       NULL,                  // default security
                       OPEN_EXISTING,         // existing file only
                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file
                       NULL);                 // no attr. template

    if (hFile == INVALID_HANDLE_VALUE) 
        _tprintf(TEXT("Terminal failure: unable to open file \"%s\" for read.\n"), argv[1]);

    printf( "Entered main, calling DLL.\n" );
    printf( "Back in main, exiting.\n" );


#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsaf        


user1952500 February 2016

You are missing the SleepEx(5000, TRUE) call from the example.

You are using async-io, in which case you will receive a callback when the read occurs. If you don't wait for the callback you may get 0 bytes read depending on when the callback is triggered.

Post Status

Asked in February 2016
Viewed 2,138 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life