Stack Overflow上一个__cxa_demangle使用例子

#include <cxxabi.h>
#include <string.h>

#include <array>
#include <iostream>

int main()
{
  const std::array<const char *, 5> bt = {
    "./src/warzone2100(_ZNK5EcKey4signEPKvm+0x98) [0x16405da]",
    "./src/warzone2100(_Z8recvPing8NETQUEUE+0x1ab) [0x126bc2d]",
    "./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI21frontendMultiMessagesEb+0x7d9) [0x11ce219]",
    "./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI3runEv+0x45) [0x11cf32b]",
    "./src/warzone2100(_Z9titleLoopv+0x1aa) [0x1480b35]",
  };
  std::cout << "Wrong way:" << std::endl << std::endl;
  for (const char* p : bt) {
    int status;
    char *demangled =  abi::__cxa_demangle(p, NULL, NULL, &status);
    std::cout << p << " " << status << std::endl;
    free(demangled);
  }

  auto trim = [](const char *in, char *out) {
    const char *begin = strchr(in, '_');
    const char *end = strchr(begin, '+');
    memcpy(out, begin, end - begin);
    out[end - begin] = '\0';
  };

  std::cout << std::endl << "Right way:" << std::endl << std::endl;
  for (const char* p : bt) {
    int status;
    char buf[1024];

    trim(p, buf);
    char *demangled =  abi::__cxa_demangle(buf, NULL, NULL, &status);
    std::cout << buf << " -> " << demangled << " " << status << std::endl;
    free(demangled);
  }
}

  执行结果

g++ -g foo.cc && ./a.out
Wrong way:

./src/warzone2100(_ZNK5EcKey4signEPKvm+0x98) [0x16405da] -2
./src/warzone2100(_Z8recvPing8NETQUEUE+0x1ab) [0x126bc2d] -2
./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI21frontendMultiMessagesEb+0x7d9) [0x11ce219] -2
./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI3runEv+0x45) [0x11cf32b] -2
./src/warzone2100(_Z9titleLoopv+0x1aa) [0x1480b35] -2

Right way:

_ZNK5EcKey4signEPKvm -> EcKey::sign(void const*, unsigned long) const 0
_Z8recvPing8NETQUEUE -> recvPing(NETQUEUE) 0
_ZN27WzMultiplayerOptionsTitleUI21frontendMultiMessagesEb -> WzMultiplayerOptionsTitleUI::frontendMultiMessages(bool) 0
_ZN27WzMultiplayerOptionsTitleUI3runEv -> WzMultiplayerOptionsTitleUI::run() 0
_Z9titleLoopv -> titleLoop() 0

  

posted @ 2024-07-16 11:10  苍洱  阅读(41)  评论(0编辑  收藏  举报