简体   繁体   English

从C ++中获取受损的符号名称

[英]get mangled symbol name from inside C++

How can I get the mangled name of a function from inside a C++ program? 如何从C ++程序中获取函数的错位名称?

For example, suppose I have a header: 例如,假设我有一个标题:

// interface.h
#ifndef INTERFACE_H
#define INTERFACE_H
typedef void (*FooFunc)(int x, int y, double z, ...more complicated stuff...);
void foo(int x, int y, double z, ...more complicated stuff...);
#endif

and I have a client program that can load plugins that implement the interface: 我有一个客户端程序,可以加载实现该接口的插件:

// client.h
#include "interface.h"
void call_plugin(so_filename)
{
    void *lib = dlopen(so_filename, ...);
    // HOW DO I IMPLEMENT THE NEXT LINE?
    static const char *mangled_name = get_mangled_name(foo);
    FooFunc func = (FooFunc)dlsym(lib, mangled_name);
    func(x, y, z, ...);
    dlclose(lib);
}

How do I write the get_mangled_name function to compute the mangled name of the foo function and return it as a string? 如何编写get_mangled_name函数来计算foo函数的get_mangled_name名称并将其作为字符串返回?

One method that comes to mind is to compile interface.o and use nm -A interface.o | grep foo 想到的一种方法是编译interface.o并使用nm -A interface.o | grep foo nm -A interface.o | grep foo to get the mangled name then copy-and-paste it as a hard-coded string into client.h , but that feels like the wrong approach. nm -A interface.o | grep foo获取受损的名称然后将其作为硬编码字符串复制并粘贴到client.h ,但这感觉就像是错误的方法。

Another method that comes to mind is to force interface.h to be a pure C interface where I marshal all of the C++ data into a big blob that's sent through a C interface and then have the C++ objects reconstructed on the other side. 想到的另一种方法是强制interface.h成为一个纯C接口,我将所有C ++数据编组成一个通过C接口发送的大块,然后在另一侧重建C ++对象。 This also feels suboptimal. 这也感觉不是最理想的。

Edit 编辑

Note that this is actually a distinct question from Getting mangled name from demangled name . 请注意,这实际上是一个与来自demangled name的mang mangled name有关的独特问题。 I'm wondering how to get at the mangled value from inside of C++ itself, at compile time, from type information available to the compiler, given a C++ identifier's name only. 我想知道如何在编译时从C ++本身内部获取损坏的值,从编译器可用的类型信息,仅给出C ++标识符的名称。

You can prevent mangling by declaring your functions as extern "C" : 您可以通过将函数声明为extern "C"来防止修改:

// interface.h
#ifndef INTERFACE_H
#define INTERFACE_H
typedef void (*FooFunc)(int x, int y, double z, ...more complicated stuff...);
extern "C" void foo(int x, int y, double z, ...more complicated stuff...);
#endif

... and making sure you #include that header file in all the source files that make up your shared library, as this declaration affects both the definition and references to the relevant function emitted by the compiler. ...并确保#include组成共享库的所有源文件中的头文件,因为此声明会影响编译器发出的相关函数的定义和引用。 Note that your function signature can still use non-POD types, such as std::string. 请注意,您的函数签名仍然可以使用非POD类型,例如std :: string。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM