5

I have tried UnDecorateSymbolName().

For example:

    #include <windows.h> 
    #include <tchar.h>
    #include <iostream>
    #pragma comment(lib,"dbghelp.lib")     

    int main(int argc, _TCHAR* argv[])  
    {  
      TCHAR szUndecorateName[256];  
      memset(szUndecorateName,0,256);  
      if (2==argc)  
      {  
        ::UnDecorateSymbolName(argv[1],szUndecorateName,256,0);  
        std::cout<<szUndecorateName<<std::endl;  
      }  
      return 0;  
    }

I modified example. It can work well.

Alan Yang
  • 65
  • 4

1 Answers1

1

I see that usually __cxa_demangle is used with argument typeid(v).name() to obtain the type of a variable v. Probably the initial question was in that sense (or similar) as it is sugested by an author comment but now when is transformed to contain the answer (and to obtain the symbolf from argv), it departed from that usage.

For the one who are searching for a solution to print the type of a variable using a __cxa_demangle replacement in C++, using MSVS 2019, Windows 10, I propose the following code:

#if defined ( _MSC_VER )
#include <windows.h> 
#include <dbghelp.h>
#pragma comment(lib,"dbghelp.lib")     
#else
#include <cxxabi.h>
#endif
#include <iostream>
#include <stdlib.h>
#include <string>

template <typename T> std::string nameofType(const T& v)
{
#if defined( _MSC_VER )
    //try to allocate a buffer as __cxa_demangle will do
    //assuming symbol name is less than 1024 bytes
    char* realname = (char*)malloc(1024 * sizeof(char));
    //if alloc was OK then set 0 first char and use UnDecorateSymbolName
    realname ? realname[0] = 0, ::UnDecorateSymbolName(typeid(v).name(), realname, 1024, 0) : 0;
#else
    int     status;
    //__cxa_demangle will allocate the buffer for the answer
    char* realname = abi::__cxa_demangle(typeid(v).name(), 0, 0, &status);
#endif
    //if null returned or 0 was not changed in something else then demangle not successful
    std::string name(realname && realname[0] ? realname : "????");
    free(realname);

    return name;
}

int main()
{
    int a_int;
    double a_double;
    
    std::cout << "nameofType a_int is:" << nameofType(a_int) << "\n" <<
        "nameofType a_double is:" << nameofType(a_double) << "\n";
    
    return 0;
}

It prints:

nameofType a_int is:int
nameofType a_double is:double

P.S. Thank you @sehe! Inspired by his answer for question 9404189.

Claudiu Cruceanu
  • 135
  • 1
  • 1
  • 10