在C ++中使用dlsym而不用外部"C"表示 [英] Using dlsym in c++ without extern "C"
问题描述
我有一个系统,在该系统中,我为用户提供了函数原型,并且用户必须实现它.现在,我使用g ++编译该文件,并使用dlopen和dlsym动态加载该文件以进一步处理它.现在,我在这里阅读:
I have a system in which I give the user a function prototype and the user has to implement it. Now, I compile this file using g++ and load it dynamically using dlopen and dlsym to process it further. Now, I read here:
要加载c ++函数,我们必须在函数之前使用extern"C".现在,问题是,我不想向用户展示事情如何进行.我不想在功能前显示用户extern"C".
that to load c++ functions we have to use extern "C" before the function. Now, the problem is, I do not want to show the user how things are working. I do not want to show the user extern "C" before the function.
有什么办法可以避免它?
Is there any way to avoid it?
推荐答案
您可以使用如果有一个C ++函数 void my_plugin(int foo)
,C ++编译器将修改该名称.知道错误的函数名称后,就可以在该名称上使用dlopen().
If you have e.g. a C++ function void my_plugin(int foo)
, the C++ compiler will mangle that name.
Once you know the mangled function name, you can use dlopen() on that name.
例如
# nm libmyplugin.so |grep my_plugin
00000000 T _Z9my_plugini
所以这里我们的函数名为_Z9my_plugini,您可以这样做
So here our function is named _Z9my_plugini , and you could do
func = dlsym(handle, "_Z9my_plugini");
传统上,不同的编译器可能以不同的方式处理名称,因此这可能非常脆弱,因此,如今,大多数C ++编译器都同意在标准平台上使用标准的方式处理名称.
Traditionally different compilers could mangle the name in different ways, so this could be quite fragile, thoug these days most C++ compilers will aggree opon a standard way of mangling the names on a given platform.
但是您的用户将是程序员,并且他们通常会了解将条目作为 extern"C"
However your users will be programmers, and they would normally have an understanding of exposing an entry to a dynamically loaded library as extern "C"
这篇关于在C ++中使用dlsym而不用外部"C"表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!