将HANDLE传递给DLL

时间:2016-02-08 07:00:00

标签: c winapi dllimport dllexport createfile

我是Win32编程的新手。 我试图将使用CreateFile()获得的HANDLE传递给DLL中的函数。 但是在尝试读取字节时,dwBytesRead表示0。 我可以将HANDLEs传递给DLL条目吗?我在这里读到[Writing DLLs],调用者的资源不属于被调用者,因此我不应该在调用者中为malloc()调用CloseHandle()或者free()之类的东西。
我的理解是否正确?请指出我正确的方向。这是代码:

的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 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]);
        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 to read from file.\n GetLastError=%08x\n", lastError);
        return lastError;
    }
    dwBytesRead = g_BytesTransferred;

    if (dwBytesRead > 0 && dwBytesRead <= BUFFERSIZE-1)
    {
        ReadBuffer[dwBytesRead]='\0';

        printf("Data read from file (%d bytes): \n", dwBytesRead);
        printf("%s\n", ReadBuffer);
    }
    else if (dwBytesRead == 0)
    {
        printf("No data read from file \n");
    }
    else
    {
        printf("\n ** Unexpected value for dwBytesRead ** \n");
    }

    printf( "Hello from a DLL!\n" );

    return( 0 );
}

1 个答案:

答案 0 :(得分:1)

您错过了示例中的SleepEx(5000, TRUE)来电。

您正在使用async-io,在这种情况下,您将在发生读取时收到回调。如果您不等待回调,则可能会读取0个字节,具体取决于触发回调的时间。