スポンサーリンク

動的ライブラリのロード方法

Windows

書いたつもりだがサイト内検索しても出てこないのでまだやってないらしい。

#include <iostream>
#include <functional>

#include <Windows.h>

int main() {
    HMODULE hModule = LoadLibraryA("MyDLL.dll");

    FARPROC func = GetProcAddress(hModule, "add");

    std::function<int(int, int)> add_func = reinterpret_cast<int(*)(int, int)>(func);
    int result = add_func(3, 5);

    std::cout << "result: " << result << std::endl;

    FreeLibrary(hModule);

    return 0;
}

Linux

mylib.so

g++ -shared -o mylib.so mylib.cpp -fPIC
extern "C" {

    int add(int a, int b) {

        return a + b;

    }

}

a.out

g++ -o a.out a.cpp -ldl
#include <iostream>

#include <functional>

#include <dlfcn.h>



int main(){

  void* handle = dlopen("./mylib.so",RTLD_LAZY);

  using add_func_ptr = int (*)(int,int);

  std::function<int(int,int)> add_func =(add_func_ptr)dlsym(handle,"add");

  int result = add_func(3,5);

  std::cout << "result:" << result << std::endl;


  dlclose(handle);

}

所感

さすがに記事が寂しすぎるのでWindowsとLinux版のコードを載せた。

あとMacOSでは拡張子を.dylibにすればよいらしい。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)


この記事のトラックバックURL: