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

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

  • 从C / C++代码可以做到这一点吗?
    我对适用于gcc / g++的解决方案感兴趣

    最佳答案

    起初,我在考虑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;
      }
    

    关于c++ - 从C代码调用共享库加载器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38812715/

    10-09 06:00
    查看更多