2009年11月28日 星期六

簡單的DLL範例

簡單的DLL範例

環境:Visual C++ 2008

建立一個新的,選擇Win32 Console Application
最後選擇DLL和Empty Porject選項

建立AddInt.h及AddInt.cpp

AddInt.h
#ifndef _ADD_INT_H_
#define _ADD_INT_H_

#define DLLExport __declspec( dllexport )

extern "C"
{
DLLExport int Add(int a, int b);
}

#endif


function必須export才能被使用,有兩種方法可以使用:
使用 __declspec這個關鍵字
建立一個Module-Definition File (.DEF)

至於為什麼要加入extern "C"
因為C++ compiler在編譯時會將function name作一些修飾也就是改名字的動作(mangle)
加入extern "C"則可保留原名

AddInt.cpp
#include "AddInt.h"

int Add(int a, int b) {
return a + b;
}


Build Project即完成,我們會在資料夾找到AddInt.dll及AddInt.lib


接著我們就寫一個程式來使用這個DLL

可以用兩種方式來使用DLL

Implicit Linking - 程式需link到AddInt.lib,並將AddInt.dll放在與程式同目錄下
#include <iostream>
#include "AddInt.h"

int main()
{
std::cout << Add(5, 10) << std::endl;

return 0;
}


Explicit Linking - 不需要AddInt.h及AddInt.Lib,僅需要AddInt.dll,但使用較為複雜。
#include <iostream>
#include <windows.h>

typedef int (*pfAddIntFunction)(int,int);

int main()
{
pfAddIntFunction pfAddInt ;

HINSTANCE hLibrary = LoadLibrary(L"AddInt.dll");

if(hLibrary)
{
pfAddInt = (pfAddIntFunction)GetProcAddress(hLibrary, "Add");

if(pfAddInt)
{
std::cout << pfAddInt(5, 10) << std::endl;
}

FreeLibrary(hLibrary);
}
else
{
std::cout << "Failed To Load Library" << std::endl;
}

return 0;
}

3 則留言:

  1. Howard,
    I have a problem to compile dll because the function name has be changed by C++ compiler and your article really helped me to solve the problem.

    Thank you very much.

    回覆刪除
  2. 終於編譯成功了!謝謝!
    不過
    AddInt.cpp 裡的 #include "DLLTutorial.h"
    應該也是 #include "AddInt.h" 吧?
    因為編譯時出現錯誤訊息。

    回覆刪除