C/C 中的 dlopen 和全局变量++
由于一些限制,我被迫在运行时加载用 C 编写的库。第三方向我提供了两个库作为静态档案,我们将其转换为共享对象。我正在使用的应用程序在运行时根据一些硬件参数加载其中一个库。不幸的是,其中一个库主要配置有全局变量。
我已经在使用 dlsym 来加载函数引用,但是我也可以使用 dlsym 来加载对这些全局变量的引用吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以使用 dlsym 访问全局变量(只要它们是导出的,而不是静态的)。下面的示例是用 C++ 和 Mac 编写的,但显然 C 也可以正常工作。
lib.cpp:
uselib.cpp
输出:
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:
uselib.cpp
Output:
是的,您可以使用 dlsym() 在动态库中找到任何导出的符号。
Yes, you can locate any exported symbol in the dynamic library using
dlsym()
.是的,你可以,而且我实际上更喜欢这样做而不是加载函数。我的标准 IOC 模型就是这样做的。
我更喜欢它,因为:
从 void* 到对象指针的转换在技术上比函数指针更安全,尽管显然使用 void* 和 dlsym 的系统必须允许您转换指针。 (微软的 GetProcAddress 返回他们自己的指针类型,在这种情况下我认为这是一个更好的选择,因为他们可以在以后需要时更改其实际含义)。
因为我在 C++ 中执行此操作,所以我可以强制任何此类导出的对象都派生自公共基类,然后我可以使用从该类到我期望的实际类的dynamic_cast。这意味着如果它不是从后面的类派生的,我可以捕获错误,从而稍后保存运行时错误。
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.