demangle c++ fn names

I was using a open source project to look at various imports in a dll and it always provided mangled function names. Here is some code I have which takes a mangled symbol and try to demangle it. For now this is MS specific.

windows

 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
typedef int (WINAPI* UnDecorateSymbolNameFn_t) (LPCSTR, LPSTR, DWORD, DWORD);
static UnDecorateSymbolNameFn_t getUnDecorateSymbolNameFn()
{
    static UnDecorateSymbolNameFn_t UnDecorateSymbolName = nullptr;
    HMODULE module = LoadLibraryA("dbghelp.dll");
    if (module != nullptr)
        UnDecorateSymbolName = (UnDecorateSymbolNameFn_t)GetProcAddress(module, "UnDecorateSymbolName");

    if (UnDecorateSymbolName == nullptr)
    {
        module = LoadLibraryA("imagehlp.dll");
        if (module != nullptr)
            UnDecorateSymbolName = (UnDecorateSymbolNameFn_t)GetProcAddress(module, "UnDecorateSymbolName");
    }

    return UnDecorateSymbolName;
}

static std::string getUndecoratedFunctionName(const std::string& mangledName)
{
   
    UnDecorateSymbolNameFn_t unDecFn = getUnDecorateSymbolNameFn();

    if (unDecFn != nullptr)
    {
        constexpr int BUFFER_LEN = 4096;
        char buffer[BUFFER_LEN];
        int errCode = unDecFn(mangledName.c_str(), buffer, BUFFER_LEN,
                             UNDNAME_COMPLETE | UNDNAME_32_BIT_DECODE | UNDNAME_NO_FUNCTION_RETURNS |
                             UNDNAME_NO_ACCESS_SPECIFIERS | UNDNAME_NO_MEMBER_TYPE | UNDNAME_NO_MS_KEYWORDS);

        if (errCode != 0)
            return std::string(buffer);
    }

    return mangledName;
}