2013-08-31 34 views
0

我是CPP的新手。我有一個創建一個DLL的Visual Studio項目。我需要編寫一個簡單的代碼來調用這個DLL中的函數。在CPP中使用DLL

到目前爲止,我瀏覽過的大多數問題都涉及到從外部應用程序調用dll的問題。

我想要一個非常簡單的教程,介紹這個概念。它加載一次dll,然後從一個簡單的代碼重複調用它的函數,而不是一個應用程序。

一個簡單的例子或指向它的鏈接將非常有幫助。

在此先感謝

+0

請澄清點:: 1.你有一個DLL A.DLL 2.你有一個exe B.EXE。 3.您希望b.exe加載a.dll並調用其導出的函數。 我理解了你的問題嗎? – Abhineet

+0

考慮我有一個DLL'myDll.dll'。我想編寫一個代碼'testDll.cpp',它將調用'myDll.dll'中的函數。我現在有什麼意義了嗎? –

+0

「在cpp中調用dll」你知道編寫b.exe的代碼將包含加載和使用a.dll的確切源代碼... – Abhineet

回答

1

的基本概念是::

  1. 調用LoadLibrary:加載DLL。
  2. GetProcAddress:獲取dll導出函數的地址。

MSDN Sample Code //假設您已正確構建帶導出函數的DLL。 //一個簡單的程序,使用LoadLibrary和 // GetProcAddress從Myputs.dll訪問myPuts。

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

typedef int (__cdecl *MYPROC)(LPWSTR); 

int main(void) 
{ 
    HINSTANCE hinstLib; 
    MYPROC ProcAdd; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 

    // Get a handle to the DLL module. 

    hinstLib = LoadLibrary(TEXT("MyPuts.dll")); 

    // If the handle is valid, try to get the function address. 

    if (hinstLib != NULL) 
    { 
     ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts"); 

     // If the function address is valid, call the function. 

     if (NULL != ProcAdd) 
     { 
      fRunTimeLinkSuccess = TRUE; 
      (ProcAdd) (L"Message sent to the DLL function\n"); 
     } 
     // Free the DLL module. 

     fFreeResult = FreeLibrary(hinstLib); 
    } 

    // If unable to call the DLL function, use an alternative. 
    if (! fRunTimeLinkSuccess) 
     printf("Message printed from executable\n"); 

    return 0; 

} 
1

你應該在dll項目中導出一個函數。

Ex: "ExportFunc" 

而你可以在其他項目中使用LoadLibrary,GetProcAddress在dll中使用funciton。 例如:

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

    typedef int (__cdecl *MYPROC)(LPWSTR); 

    int main(void) 

    { 
    HINSTANCE hinstLib; 
    MYPROC ProcAdd; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 

    // Get a handle to the DLL module. 

    hinstLib = LoadLibrary(TEXT("DllName.dll")); 

    // If the handle is valid, try to get the function address. 

    if (hinstLib != NULL) 
    { 
     ProcAdd = (MYPRO`enter code here`C) GetProcAddress(hinstLib, "ExportFunction"); 

     // If the function address is valid, call the function. 

     if (NULL != ProcAdd) 
     { 
      fRunTimeLinkSuccess = TRUE; 
      (ProcAdd) (L"Message sent to the DLL function\n"); 
     } 
     // Free the DLL module. 

     fFreeResult = FreeLibrary(hinstLib); 
    } 

    // If unable to call the DLL function, use an alternative. 
    if (! fRunTimeLinkSuccess) 
     printf("Message printed from executable\n"); 

    return 0; 

}