Using dlsym in c++ without extern quot;Cquot;(在没有外部“C的情况下在 c++ 中使用 dlsym)
问题描述
我有一个系统,我给用户一个函数原型,用户必须实现它.现在,我使用 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++ dlopen小方法
要加载 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?
推荐答案
你可以使用 mangled C++ 直接命名.
You can use the mangled C++ name directly.
如果你有例如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"的情况下在 c++ 中使用 dlsym的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在没有外部“C"的情况下在 c++ 中使用 dlsym


- Easyx实现扫雷游戏 2023-02-06
- ubuntu下C/C++获取剩余内存 2023-09-18
- Qt计时器使用方法详解 2023-05-30
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- C++ 数据结构超详细讲解顺序表 2023-03-25
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C语言qsort()函数的使用方法详解 2023-04-26
- C语言详解float类型在内存中的存储方式 2023-03-27
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09