summaryrefslogtreecommitdiff
path: root/src/TypeInfo.hpp
blob: dc718ff3b8acbc9edcbea8ac619e3308875bcef9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#ifndef __TYPEINFO_H
#define __TYPEINFO_H

#include <typeinfo>
#include <string>
#include <stdexcept>
#include <cstdlib>

#if defined( __GNUG__ ) && defined( __GLIBCXX__ )

#include <cxxabi.h>

std::string demangle( const std::type_info &info )
{
	enum { BUFLEN = 200 };
	char *buf;
	std::size_t buflen = BUFLEN;
	int status;
	char *res;
	
	// pass a malloced buffer (required by cxa_demangle)
	buf = (char *)malloc( BUFLEN );
	
	// res may point to buf or be realloced depending on whether the
	// demangling had enough space or not
	res = __cxxabiv1::__cxa_demangle( info.name( ), buf, &buflen, &status );
	
	// throw exception if this goes wrong, because we don't want to have
	// have code reacting on failed demangling or wrong type information!
	if( status != 0 || res == NULL ) {
		throw std::runtime_error( "__cxa_demangle failed!" );
	}
	
	// construct string on stack and return it, free original buffer
	std::string s( res );
	free( res );
	
	return s;
}
	
#else

#error "C++ demangling not ported!"

#endif // defined( __GNUG__ ) && defined( __GLIBCXX__ )

#endif // __TYPEINFO_H