2014-01-15 70 views
0

我不太瞭解DLL,所以我構建了一個簡單的示例,我可以幫助解答一些問題。我在這裏有一個簡單的dll。如何在運行時鏈接期間從我的DLL中調用函數?

// HelloDLL.cpp 

#include "stdafx.h" 

int  __declspec(dllexport) Hello(int x, int y);  

int Hello(int x, int y) 
{ 
    return (x + y); 
} 

我怎麼會叫Hello(int x, int y)功能在一個單獨的程序,一旦我已經運行LoadLibrary()?以下是我迄今爲止的一個粗略佈局,但我不確定我擁有的是否正確,如果是,請繼續。

// UsingHelloDLL.cpp 

#include "stdafx.h" 
#include <windows.h> 

int main(void) 
{ 
    HINSTANCE hinstLib; 

    // Get the dll 
    hinstLib = LoadLibrary(TEXT("HelloDLL.dll")); 

    // If we got the dll, then get the function 
    if (hinstLib != NULL) 
    { 
     // 
     // code to handle function call goes here. 
     // 

     // Free the dll when we're done 
     FreeLibrary(hinstLib); 
    } 
    // else print a message saying we weren't able to get the dll 
    printf("Could not load HelloDLL.dll\n"); 

    return 0; 
} 

任何人都可以幫我瞭解如何處理函數調用?任何特殊情況下,我應該知道未來使用dll的情況?

+0

'GetProcAddress的()'會是你要找的內容;它記錄在[MSDN](http://msdn.microsoft.com)。 –

回答

1

加載庫後,你需要的是找到函數指針。微軟提供的功能是GetProcAdderess。不幸的是,你必須知道函數原型。如果你不知道,我們會一直到COM/DCOM等等,可能超出你的範圍。

FARPROC WINAPI GetProcAddress(_In_ HMODULE hModule, _In_ LPCSTR lpProcName); 

因此,在你的榜樣,你做什麼nromally是這樣的:

typedef int (*THelloFunc)(int,int); //This define the function prototype 

if (hinstLib != NULL) 
{ 
    // 
    // code to handle function call goes here. 
    // 

    THelloFunc f = (THelloFunc)GetProcAddress(hinstLib ,"Hello"); 

    if (f != NULL) 
     f(1, 2); 

    // Free the dll when we're done 
    FreeLibrary(hinstLib); 
} 
+0

非常感謝您的回覆。這是否意味着我將不得不爲每個函數都鍵入一個函數原型,無論我將使用哪個dll? – user3192654

+0

是的。你必須知道函數原型。但是,這實際上不是問題。因爲調用進程和dll會共享一個通用的頭文件。它可以在那裏方便地定義。感謝您的積極評價。 – user3195397

相關問題