2

Basically I would like to look up a function in a shared object in a platform independent way: I don't want to deal with LoadLibrary/GetProcAddress or dlopen details.

Is there a library that hides the process of looking up a function pointer in shared objects on various operating systems? I would like simply to provide the shared object/dll name and the function name and obtain a C function pointer to invoke that function.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Giovanni
  • 21
  • 1

2 Answers2

6

There is no library because using dlsym or GetProcAddress is so simple that it is not worth to be factored out in a separate library. But it is a part of many libraries.

Heres a quick Copy&Paste from the FOX GUI Toolkit:

void* fxdllOpen(const FXchar *dllname){
  if(dllname){
#ifndef WIN32
#ifdef HAVE_SHL_LOAD    // HP-UX
    return shl_load(dllname,BIND_IMMEDIATE|BIND_NONFATAL|DYNAMIC_PATH,0L);
#else
#ifdef DL_LAZY      // OpenBSD
    return dlopen(dllname,DL_LAZY);
#else           // POSIX
    return dlopen(dllname,RTLD_NOW|RTLD_GLOBAL);
#endif
#endif
#else                   // WIN32
    return LoadLibraryExA(dllname,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
#endif
    }
  return NULL;
  }


void fxdllClose(void* dllhandle){
  if(dllhandle){
#ifndef WIN32
#ifdef HAVE_SHL_LOAD    // HP-UX
    shl_unload((shl_t)dllhandle);
#else           // POSIX
    dlclose(dllhandle);
#endif
#else                   // WIN32
    FreeLibrary((HMODULE)dllhandle);
#endif
    }
  }


void* fxdllSymbol(void* dllhandle,const FXchar* dllsymbol){
  if(dllhandle && dllsymbol){
#ifndef WIN32
#ifdef HAVE_SHL_LOAD    // HP-UX
    void* address=NULL;
    if(shl_findsym((shl_t*)&dllhandle,dllsymbol,TYPE_UNDEFINED,&address)==0) return address;
#else           // POSIX
    return dlsym(dllhandle,dllsymbol);
#endif
#else                   // WIN32
    return (void*)GetProcAddress((HMODULE)dllhandle,dllsymbol);
#endif
    }
  return NULL;
  }
Lothar
  • 12,537
  • 6
  • 72
  • 121
2

Take a look at how it was done in boost, interprocess/detail/os_file_functions.hpp. No magic here, #ifdef is needed.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536