我有一个共享库,我想在我的程序中加载两次。 用例如下:
C / C ++代码有没有办法做到这一点? 我对使用gcc / g ++
的解决方案感兴趣答案 0 :(得分:4)
起初我在考虑LoadLibrary,GetProcAddress和FreeLibrary但后来我提到你需要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;
}