1、封装成python可调用的so:
#include <Python.h>
#include <cxxabi.h>
#include <cstdlib> // 添加此行以便使用 free 函数
static PyObject* demangle(PyObject* self, PyObject* args) {
const char* mangledName;
if (!PyArg_ParseTuple(args, "s", &mangledName)) {
return NULL;
}
int status;
char* demangledName = abi::__cxa_demangle(mangledName, NULL, NULL, &status); // 修改 nullptr 为 NULL
if (status == 0) {
PyObject* result = Py_BuildValue("s", demangledName);
free(demangledName); // 释放内存
return result;
} else {
PyErr_SetString(PyExc_RuntimeError, "Demangling failed.");
return NULL;
}
}
static PyMethodDef DemangleMethods[] = {
{"demangle", demangle, METH_VARARGS, "Demangle a mangled C++ name."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef demanglemodule = {
PyModuleDef_HEAD_INIT,
"demangle",
NULL,
-1,
DemangleMethods
};
PyMODINIT_FUNC PyInit_demangle(void) {
return PyModule_Create(&demanglemodule);
}
编译: g++ -shared -o demangle.so demangle.cpp -I/home/work/.pyenv/versions/3.8.0/include/python3.8 -L/home/work/.pyenv/versions/3.8.0/lib -lpython3.8 -fPIC
##2、python 库
import cxxfilt
import sys
import re
mangled_name = sys.argv[1]
print("input: ", mangled_name)
# 尝试解码字符串
func_name = cxxfilt.demangle(mangled_name)
print(func_name)
pattern = r'::(\w+)\('
matches = re.findall(pattern, func_name)
if matches:
func_name = matches[0]
print(func_name)