在没有外部“C"的情况下在 c++ 中使用 dlsym [英] Using dlsym in c++ without extern "C"

查看:61
本文介绍了在没有外部“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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆