从c代码调用共享库加载器

时间:2016-08-07 09:25:13

标签: c++ c gcc

我有一个共享库,我想在我的程序中加载两次。 用例如下:

  • 打开程序(和加载库)
  • 从库中调用函数F1()
  • 从程序中分离库
  • 再次加载库并重新初始化所有变量
  • 再次从库中调用函数F1()

C / C ++代码有没有办法做到这一点? 我对使用gcc / g ++

的解决方案感兴趣

1 个答案:

答案 0 :(得分:4)

起初我在考虑LoadLibraryGetProcAddressFreeLibrary但后来我提到你需要gcc/g++看起来像你需要* NIX解决方案。所以我只是从here偷了解决方案:

<强> loadlib.h

#ifndef  __LOADLIB_H
#define  __LOADLIB_H

#ifdef UNIX
#include <dlfcn.h>
#endif 

#include <iostream>
using namespace std;

typedef void* (*funcPtr)();

#ifdef UNIX
#  define IMPORT_DIRECTIVE __attribute__((__visibility__("default")))
#  define CALL  
#else
#  define IMPORT_DIRECTIVE __declspec(dllimport) 
#  define CALL __stdcall
#endif

extern "C" {
  IMPORT_DIRECTIVE void* CALL LoadLibraryA(const char* sLibName); 
  IMPORT_DIRECTIVE funcPtr CALL GetProcAddress(
                                    void* hModule, const char* lpProcName);
  IMPORT_DIRECTIVE bool CALL  FreeLibrary(void* hLib);
}

#endif

<强> Loadlib.cpp

#include "loadlib.h"

int main(int argc, char* argv[])
  {
  #ifndef UNIX
    char* fileName = "hello.dll";
    void* libraryHandle = LoadLibraryA(fileName);
    if (libraryHandle == NULL)
      cout << "dll not found" << endl;
    else  // make a call to "printHello" from the hello.dll 
      (GetProcAddress(libraryHandle, "printHello"))();
    FreeLibrary(libraryHandle);
#else // unix
    void (*voidfnc)(); 
    char* fileName = "hello.so";
    void* libraryHandle = dlopen(fileName, RTLD_LAZY);
    if (libraryHandle == NULL)
      cout << "shared object not found" << endl;
    else  // make a call to "printHello" from the hello.so
      {
      voidfnc = (void (*)())dlsym(libraryHandle, "printHello"); 
      (*voidfnc)();
      }
    dlclose(libraryHandle);
  #endif

  return 0;
  }