跳到主要內容

Dynamically loaded libraries 動態載入庫 #2 C++

Dynamically loaded libraries 動態載入庫 #2 C++

這篇寫如何寫C++的動態載入庫,因為C++編譯器會修飾函式名稱,所以不能直接用C的方式寫庫
範例函式庫
mylib.h
extern "C" {
    void hello();
    void world();
}
與C的不同處是這裡要加上extern "C" {}包住不希望被編譯器修飾的函式
hello.cpp
#include "mylib.h"
#include <iostream>

void hello(){
    std::cout << "Hello" ;
}
world.cpp
#include "mylib.h"
#include <iostream>

void world(){
    std::cout << "World" ;
}
編譯
$ g++ -c -fPIC hello.cpp world.cpp
$ g++ -shared -o libmylib.so hello.o world.o
編譯的方式除了從gcc改為g++之外,沒有其他改變
使用方式
main.cpp
int main() {
    void* handle = dlopen("./libmylib.so", RTLD_LAZY);

    void (*f1)() = (void (*)()) dlsym(handle, "hello");
    void (*f2)() = (void (*)()) dlsym(handle, "world");

    f1();
    f2();

    dlclose(handle);
    return 0;
}
使用方式和C一模一樣,這裡假設不會出錯誤
編譯
編譯時要一樣連結 libdl,使用 -ldl
$ g++ main.cpp -ldl
執行
$ ./a.out
結果
HelloWorld

動態載入類別

這篇只寫到 C++ 使用動態載入函式庫並呼叫函式,並沒有提到載入類別,
那是因為 libdl 是 C 函式庫,本來就不包含類別的功能,
因此必須用其他手段來達成這樣的功能,
正好物件導向的多形可以達成這樣的功能,
至於如何實作寫在下一篇

留言

  1. 請問一下,我應該怎麼匯入以下這個函數?
    __declspec(dllexport) char __cdecl *GetFileSHA1(char *FileNameInPut, char *outSHA1, char *outError)
    這是mingw編譯的

    回覆刪除

張貼留言

這個網誌中的熱門文章

Windows 編譯 OpenSSL 1.1.0

Windows 編譯 OpenSSL 1.1.0 OpenSSL 的編譯方式在原始碼中的文件 NOTES.WIM 提到詳細的介紹在 INSTALL 文件中。 需要使用 Visual Studio IDE OpenSSL 原始碼 ActivePerl 或其他 Perl 執行環境 本文使用 Windows 10 版本1703 組建 15063.413 Visual Studio 2017 Community OpenSSL 1.1.0f ActivePerl 5.24.1.2402-MSWin32-x64-401627 32位元與64位元要分開編譯,release與debug也要分開 因為 openssl 的 Makefile 沒有自動處理四種版本,若不各自編譯會出錯, 複製四分 openssl 原始碼,分為 32 位元與 64 位元及 release 與 debug,例: c:\openssl-x86 、 c:\openssl-x86-dbg 、 c:\openssl-x64 、 c:\openssl-x64-dbg x86 以系統管理員權限執行 x86 Native Tools Command Prompt for VS 2017 ,通常安裝 Visual Studio IDE 時會新增捷徑到開始列表 ,而 2017 Community 版本的檔案位置為 C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat ,不能直接執行 vcvars32.bat , 應該以命令提示字元(cmd.exe)執行 cd 到解壓縮的openssl資料夾內,例: cd c:\openssl-x86 執行以下 perl Configure VC-WIN32 no-asm --prefix=C:\openssl-msvc2017-x86 mkdir C:\openssl-msvc2017-x86 nmake nmake test nmake install 這樣會輸出在 C:\openssl-msvc2017-x86 x86-debug 以系統管理員權限執行 x86 Nati...