1. 程式人生 > >如何呼叫DLL中的函式

如何呼叫DLL中的函式

如何呼叫 DLL 中的函式

在 DLL工程中的 cpp中函式定義如下:

extern "C" _declspec (dllexport )

      int add(int a, char b)

{

      return a + b;

}

一:顯示連結

呼叫的 DLL的主工程的 main檔案中程式碼如下:

#include <stdio.h>

#include <Windows.h>

#include <tchar.h>

int main()

{

      HMODULE hModule = NULL;

      typedef int (*Func)(int

 a, int b);

      // 動態載入 DLL 檔案

      hModule = LoadLibrary(_TEXT("..//Debug//FuncDll.dll" ));

      // 獲取 add 函式地址

      Func fAdd = (Func)GetProcAddress(hModule, "add" );

      // 使用函式指標

      printf("%d/n" , fAdd(5, 2));

      // 最後記得要釋放指標

      FreeLibrary(hModule);

      return 0;

}

二:隱式連結:

呼叫的 DLL的主工程的 main檔案中程式碼如下:

#include <stdio.h>

#include <Windows.h>

#include <tchar.h>

// 先把 lib 連結進來

#pragma comment (lib , "..//Debug//FuncDll.lib" )

// 外部宣告的 add 函式

extern "C" _declspec (dllimport )

      int add(int a, char b);

int main()

{

      // 直接呼叫 add 函式

      printf("%d/n" , add(5, 2));

      return 0;

}