這篇也是寫給我自已看的...

 

[製作DLL]

首先,建立一個DLL專案

再來,加入.cpp 及 .h檔

 

在 DoDll.h 中加入下段程式碼

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

 

在 DoDll.cpp 中加入下段程式碼

#include <cstdio>
#include "DoDll.h"

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

 

最後,再compile 後所輸出的 DoDll.dll 即為我們所要的檔案 (DoDll.h中會有我們要使用的API名稱,所以很重要...)

 

 

 

 

[使用DLL]

使用DoDll.dll 的方法

首先,建立一個專案

再來,將DoDll.dll 及DoDll.h放入該專案資料夾中

 

將DoDll.h 加入至標頭檔中

在UseDll.h 中加入下段程式碼

#include "DoDll.h"

typedef int (*fpAdd)(int a, int b);

 

在UseDll.cpp 中加入下段程式碼

#include <cstdio>
#include <windows.h>
#include "UseDll.h"

int main()
{
    HINSTANCE handler = LoadLibrary(".\\DoDll.dll");
    if(handler == NULL)
    {
        printf("Load Dll Error\n");
        system("pause");
    }

    fpAdd fcAdd = (fpAdd)GetProcAddress(handler, "Add");
    if(fcAdd == NULL)
    {
        printf("Load Function Error\n");
        system("pause");
    }

    int Value = 0;

    Value = fcAdd(5,2);

    printf("Value = %d\n", Value);
    system("pause");

    return true;
}

 

1. 請記住一定要include <window.h> 才能用HISTANCE 物件

2. 請用一個HISTANCE 變數來接dll

3. 用UseDll.h 中接的fpAdd 來宣告一個變數,並用它來接Dll中我們要使用的API

4. 若DLL 及 API都有正確的Load到,就可以用啦

 

懶人用法 ~


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Joh 的頭像
    Joh

    冰雨小記

    Joh 發表在 痞客邦 留言(1) 人氣()