简体   繁体   English

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

[英]invoking shared library loader from c code

I have a shared library that I would like to load twice in my program. 我有一个共享库,我想在我的程序中加载两次。 The use case is as following: 用例如下:

  • Open program (and load library) 打开程序(和加载库)
  • Call Function F1() from library 从库中调用函数F1()
  • detach library from program 从程序中分离库
  • load library again and re-initialize all variables 再次加载库并重新初始化所有变量
  • Call Function F1() from library again 再次从库中调用函数F1()

Is there a way from C/C++ code to do this? 有没有办法从C / C ++代码执行此操作? I am interested in a solution that works with gcc/g++ 我对使用gcc / g ++的解决方案感兴趣

At first I was thinking about LoadLibrary , GetProcAddress and FreeLibrary but then I mentioned that you want gcc/g++ , which looks like you need *NIX solution. 起初我在考虑LoadLibraryGetProcAddressFreeLibrary,但之后我提到你想要gcc/g++看起来你需要* NIX解决方案。 So I just have stolen solution from here : 所以我只是从这里偷了解决方案:

loadlib.h 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 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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM