Home >Backend Development >C++ >How can I demangle std::type_info::name to reveal the underlying type in C ?

How can I demangle std::type_info::name to reveal the underlying type in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 11:38:11425browse

How can I demangle std::type_info::name to reveal the underlying type in C  ?

De-Mangler for std::type_info::name: Unveiling the Demystified Name

The name mangled by std::type_info remains enigmatic, rendering it challenging to comprehend the underlying type. The quest for a solution that demangles this enigma has led to the exploration of various approaches.

Demangling the Mangled Name

One solution leverages C 11's powerful features and g 's libstdc library through the abi::__cxa_demangle function. This function decodes the mangled name, returning a human-readable string.

C 11 Implementation

In the C 11 implementation, the demangle function is included in the "type.hpp" header file, and the actual demangling logic resides in "type.cpp." The following code snippet illustrates:

#include "type.hpp"

std::string demangle(const char* name) {

    int status = -4; 
    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, NULL, NULL, &status),
        std::free
    };

    return (status==0) ? res.get() : name ;
}

C 98 Compatible Version

For those not utilizing C 11, an alternative remains available. The C 98 compatible implementation in "type.cpp" employs a different technique to demangle the name:

#include "type.hpp"

struct handle {
    char* p;
    handle(char* ptr) : p(ptr) { }
    ~handle() { std::free(p); }
};

std::string demangle(const char* name) {

    int status = -4; 
    handle result( abi::__cxa_demangle(name, NULL, NULL, &status) );

    return (status==0) ? result.p : name ;
}

Usage and Considerations

The demangled name can be retrieved using the type function, which accepts a reference to the type to be demangled. The following code demonstrates its usage:

#include "type.hpp"
struct Base { virtual ~Base() {} };
struct Derived : public Base { };

int main() {
    Base* ptr_base = new Derived();
    std::cout << "Type of ptr_base: " << type(ptr_base) << std::endl;
    std::cout << "Type of pointee: " << type(*ptr_base) << std::endl;
    delete ptr_base;
}

Conclusion

With these techniques, developers can now unveil the hidden identities of mangled type names, gaining a clearer understanding of the types involved in their code.

The above is the detailed content of How can I demangle std::type_info::name to reveal the underlying type in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn