如何从共享库中调用函数?
从共享库/dll 调用函数的最简单、最安全的方法是什么?我最感兴趣的是在linux上做这件事,但如果有一种独立于平台的方式那就更好了。
有人可以提供示例代码来展示如何进行以下工作,其中用户将自己的 foo
版本编译到共享库中吗?
// function prototype, implementation loaded at runtime:
std::string foo(const std::string);
int main(int argc, char** argv) {
LoadLibrary(argv[1]); // loads library implementing foo
std::cout << "Result: " << foo("test");
return 0;
}
顺便说一句,我知道如何编译共享库(foo.so
),我只需要知道一种在运行时加载它的简单方法。
What is the easiest and safest way to call a function from a shared library / dll? I am mostly interested in doing this on linux, but it would be better if there were a platform-independent way.
Could someone provide example code to show how to make the following work, where the user has compiled his own version of foo
into a shared library?
// function prototype, implementation loaded at runtime:
std::string foo(const std::string);
int main(int argc, char** argv) {
LoadLibrary(argv[1]); // loads library implementing foo
std::cout << "Result: " << foo("test");
return 0;
}
BTW, I know how to compile the shared lib (foo.so
), I just need to know an easy way to load it at runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意:您正在围绕库调用传递 C++ 对象(在本例中为 STL 字符串)。此级别没有标准 C++ ABI,因此要么尝试避免传递 C++ 对象,或者确保您的库和程序都是使用相同的编译器构建的(最好是同一台机器上的相同编译器,以避免任何与配置相关的微妙意外。)
不要忘记声明您导出的方法
extern "C"
< /a> 在你的库代码中。上面已经说过了,这里是一些实现您所说的想要实现的目标的代码:
您可以进一步抽象:
NOTE: You are passing C++ objects (in this case STL strings) around library calls. There is no standard C++ ABI at this level, so either try to avoid passing C++ objects around, or ensure that both your library and your program have been built with the same compiler (ideally the same compiler on the same machine, to avoid any subtle configuration-related surprises.)
Do not forget to declare your exported methods
extern "C"
inside your library code.The above having been said, here is some code implementing what you said you want to achieve:
You can abstract this further:
LoadLibrary 是一个用于加载 DLL 的 Windows 函数。您可以使用 GetProcAddress 检查符号是否存在。在 Linux/Unix 上,您需要 dlopen/dlsym。要在跨平台中执行此操作,您可以编写一个函数,使用预处理器调用这些方法中的任何一个,因此,类似于:
这是实现此类事情的一种方法。您还可以通过在自己的源代码树中包含不同的标头来实现特定平台的函数实现。这可能是一个更好的方法。无论哪种情况,我们的想法都是从底层 API 中进行抽象。
LoadLibrary is a Windows function for loading DLLs. You can check for symbol existence with GetProcAddress. On Linux/Unix you want dlopen/dlsym. To do this in cross platform, you could write a function that calls either of these methods using pre-processor, so, something like:
This is one way to achieve this sort of thing. You could also do it by including a different header in your own source tree for specific platform implementations of functions. This is probably a better way. In either case the idea is to abstract from the underlying API.
在 Linux 上,您需要使用 dlsym。请参阅本页末尾的示例。
在窗口上:GetProcAddress。
On Linux you need to use dlsym. See an example at the end of the page.
On Window: GetProcAddress.