Dlopen and global variables in C / C ++

Due to some limitations, I have to load a library written in C at runtime. The third party provides me with two libraries as static archives, which we turn into common objects. The application I'm working with loads one of the libraries at runtime based on some hardware options. Unfortunately, one of the libraries is mostly configured with global variables.

I already use dlsym to load references to functions, but can I use dlsym to load references to these global variables?

+8
c ++ c dlopen
source share
3 answers

Yes, you can use dlsym to access global ones (as long as they are exported, 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 
+10
source share

Yes, you can find any exported character in a dynamic library using dlsym() .

+1
source share

Yes, you can and I prefer to do this rather than loading functions. My standard IOC model does just that.

I prefer it because:

  • Casting from void * to a pointer to an object is technically safer than a pointer to a function, although obviously, a system using void * with dlsym should allow you to convert the pointer. (Microsoft GetProcAddress returns its own pointer type, which in this case I consider to be the best choice, because they can change the actual value of this later if they need to).

  • Since I do this in C ++, I can ensure that any such exported object comes from a common base class, and then I can use dynamic_cast from this class for the actual one that I expect. This means that I can catch an error if it does not derive from a later class, subsequently saving runtime errors.

+1
source share

Source: https://habr.com/ru/post/650983/


All Articles