C++ Name Mangling Library for Python [closed]

2020-03-01 10:49发布

问题:


Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 3 years ago.

I'd like to mangle and demangle C++ function names in a Python program. Is there anything like that available? I searched for hours now, perhaps I'm lucky here...

回答1:

You most likely don't want to be doing this in Python. As an aside you probably shouldn't be exporting mangled names from your DLLs since it makes it hard to use for anyone with a different compiler.

If you have to use mangled names then just hard code them in your Python code. If you were going to do mangling in Python code then you'd have to:

  1. Know the implementation specific rules for the compiler in question.
  2. Specify in Python the C++ function signature for each function.

It seems highly unlikely to me that coding all this up in Python would be better than simply hard coding the mangled names.



回答2:

If you want to demangle names, eg. for display, then you can create a pipe that runs c++filt.

def demangle(names):
    args = ['c++filt']
    args.extend(names)
    pipe = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout, _ = pipe.communicate()
    demangled = stdout.split("\n")

    # Each line ends with a newline, so the final entry of the split output
    # will always be ''.
    assert len(demangled) == len(names)+1
    return demangled[:-1]

print demangle(['_ZNSt15basic_stringbufIcSt11char_traitsIcESaIcEE17_M_stringbuf_initESt13_Ios_Openmode',
    '_ZNSt15basic_stringbufIcSt11char_traitsIcESaIcEE6setbufEPci'])

You can specify arguments to c++filt if you need to use a specific demangling method.

Mangling a name is much harder, and probably can't be done without knowing the definitions of the types involved.