Home DLL 隱式連結(Implicit Linking)(中文)
Post
Cancel

DLL 隱式連結(Implicit Linking)(中文)

需要 .lib .dll and header

DLL 專案設定:

DLL 真的是好用,但是設定很繁瑣,也很容易出錯。 以下的例子會示範

  1. export dll function
  2. export dll struct
  3. export dll class
  4. export dll template function

應該很完整(有誠意)了吧

建立 DLL 專案:

Desktop View

Desktop View

打開屬性頁確認一下組態類型為 動態程式庫 (.dll)

Desktop View

讓它輸出到獨立的資料夾,主要是之後讓 .lib 不要隨著執行檔一起打包出去

Desktop View

輸出如下

Desktop View

為什麼?

儘管 .lib 檔案本身不包含實際的函式實作,但它包含了函式的名稱和對應的 DLL 中的地址。因此,如果有人能夠獲取到 .lib 檔案,他們就可以查看到 DLL 中導出函式的名稱和地址,從而有可能逆向工程 DLL 的實作。

但是 DLL 要和 exe 放在一起才可以執行,所以使用建置完複製檔案的作法就可以了 只複製 DLL 檔

Desktop View

定義於 .h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#pragma once
// export function
extern "C" __declspec(dllexport) int AddFunction(int a, int b);

struct __declspec(dllexport) MyStruct {
    int number1;
    int number2;
};

class __declspec(dllexport) MyClass {
public:

    MyClass();

    int MultiplyBy10(int a);
};

template <typename T>
__declspec(dllexport) T AddTemplate(T a, T b)
{
    return a + b;
};

實作於 .cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "pch.h"
#include "MyDLL.h"

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

MyClass::MyClass()
{
}

int MyClass::MultiplyBy10(int a)
{
    return a*10;
}

好啦,上述已經成功做好 Dll 了,接下來要如何使用 Dll ?

建立使用 DLL 的專案:

我們建立一個 console 專案來示範。

Desktop View

指定這個專案要使用的 lib 目錄位置(建議使用相對目錄)

Desktop View

指定連結器要使用的 lib 名稱

Desktop View

資料夾如下

Desktop View

在 VS 下看到的樣子

Desktop View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include "../Dll1/MyDLL.h"
int main()
{
    std::cout << "DLL demo : \n";

    std::cout << "-----------------" << std::endl << std::endl;

    std::cout << "Call AddFunction in DLL : " << AddFunction(5, 5) << std::endl<< std::endl;

    MyStruct myStruct{1,5};
    std::cout << "Use MyStruct in DLL : " << myStruct.number1 << std::endl;
    std::cout << "Use MyStruct in DLL : " << myStruct.number2 << std::endl << std::endl;

    auto myClass = new MyClass();

    std::cout << "Use MyClass in DLL : " << myClass->MultiplyBy10(10) << std::endl << std::endl;

    std::cout << "Call AddTemplate in DLL : " << AddTemplate(1.1, 2.3) << std::endl << std::endl;

    std::cout << "Call AddTemplate in DLL : " << AddTemplate(0.1f, 0.3f) << std::endl << std::endl;

    system("pause");
}

最後輸出資料夾

Desktop View

結果

Desktop View

過程好繁瑣,呼,感謝你看到最後,哈。

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍

DLL Implicit Linking(English)

DLL Explicit Linking(English)