Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dlopen and global variables in C/C++

Tags:

c++

c

dlopen

Due to some restrictions I am being forced to load a library written in C at runtime. A third party provides two library to me as static archives which we turn into shared objects. The application I'm working with loads one of the libraries at runtime based on some hardware parameters. Unfortunately one of the libraries is configured largely with global variables.

I am already using dlsym to load function references but can I used dlsym to load references to these global variables as well?

like image 951
mjn12 Avatar asked Jan 12 '11 16:01

mjn12


1 Answers

Yes, you can use dlsym to access globals (as long as they are exported, and not static). The example below is in C++ and Mac, but obviously C will work fine.

lib.cpp:

extern "C" {
  int barleyCorn = 12;
}

uselib.cpp

#include <dlfcn.h>
#include <iostream>
using namespace std;

main()
{
  void * f = dlopen ("lib.dylib", RTLD_NOW);
  void * obj = dlsym (f, "barleyCorn");
  int * ptr = (int *) obj;
  cout << *ptr << endl;
}

Output:

% ./a.out
12
like image 163
EmeryBerger Avatar answered Oct 10 '22 11:10

EmeryBerger