dlopen and global variables in C/C++

柔情痞子 提交于 2019-12-20 20:05:15

问题


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?


回答1:


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



回答2:


Yes, you can locate any exported symbol in the dynamic library using dlsym().




回答3:


Yes you can and I actually prefer to do this rather than load functions. My standard IOC model does it that way.

I prefer it because:

  • The cast from a void* to a pointer to an object is technically safer than that to a function pointer, although obviously the system that uses void* with dlsym must allow you to convert the pointer. (Microsoft's GetProcAddress returns their own pointer type, which in this case I think is a better choice because they can change the actual meaning of this later if they need to).

  • Because I do it in C++ I can enforce that any such exported object derives from a common base class, and then I can use dynamic_cast from that class to the actual one I expect it to be. This means I can catch an error if it does not derive from the later class, saving runtime errors later.



来源:https://stackoverflow.com/questions/4671328/dlopen-and-global-variables-in-c-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!