Introduction
A macro that gets function return type. Works for visual studio compilers. Useful for debug prints. You can modify it to show other parts of the function prototype.
Background
The predefined macros __FILE__
, __LINE__
, __FUNCTION__
etc. allow some easy printing of debug information but sometimes you want
to know the type of function or it's arguments.
For this you've got __FUNCDNAME__
. I made this example for a friend and thought I'd share it with you. It unmangles the function name returned
by __FUNCDNAME__
. And copies the return type to a char array.
The code
******* Step 1 - Add the following code: *******
#include "Dbghelp.h"
#define CLEANUP_UNDNAME_FLAGS (UNDNAME_NO_ACCESS_SPECIFIERS | UNDNAME_NO_ALLOCATION_LANGUAGE | \
UNDNAME_NO_ALLOCATION_MODEL |
UNDNAME_NO_CV_THISTYPE | UNDNAME_NO_LEADING_UNDERSCORES | \
UNDNAME_NO_MEMBER_TYPE | UNDNAME_NO_MS_KEYWORDS |
UNDNAME_NO_MS_THISTYPE | \
UNDNAME_NO_RETURN_UDT_MODEL | UNDNAME_NO_SPECIAL_SYMS | \
UNDNAME_NO_THISTYPE | UNDNAME_NO_THROW_SIGNATURES)
#define GET_UNMANGLED_FUNCTYPE(x,sz) \
char* _mangled_func_name_ = __FUNCDNAME__; \
char _unmangled_no_ret_type_[sz]; \
DWORD rc = UnDecorateSymbolName(_mangled_func_name_, x, sz-1, CLEANUP_UNDNAME_FLAGS); \
DWORD rc2 = UnDecorateSymbolName(_mangled_func_name_, _unmangled_no_ret_type_,
sz-1, CLEANUP_UNDNAME_FLAGS | UNDNAME_NO_FUNCTION_RETURNS)+1; \
if (rc2 < rc) \
{ \
x[rc-rc2] = '\0'; \
}
******* Step 2 - Use macro in function body as follows: *******
unsigned void* foo()
{
char funcType [1024];
GET_UNMANGLED_FUNCTYPE(funcType, 1024);
return NULL;
}
unsigned int bar()
{
char funcType [1024];
GET_UNMANGLED_FUNCTYPE(funcType, 1024);
return 0;
}
void foobar()
{
char funcType [1024];
GET_UNMANGLED_FUNCTYPE(funcType, 1024);
}
******* Step 3 - Add Dbghelp lib dependency to linker: *******
This can be done by adding the following to the linker Additional inputs:
Dbghelp.lib
Or by adding the following line to one of the .cpp files in the project:
#pragma comment( lib, "Dbghelp" )
Note
- For simplicity - I assume that the demangling left the function return type at the beginning of the demangled func name. I'm not sure this will always be the case.
- As far as I can tell from my test - this does not work in the main() function! instead of return value type - I got "main".