我在 C++ 中有一个函数,它接收一个初始化的类作为 PyObject。python类是:
class Expression:
def __init__(self, obj):
self.obj = obj
def get_source(self):
#Check if the object whose source is being obtained is a function.
if inspect.isfunction(self.obj):
source = inspect.getsourcelines(self.obj)[0][1:]
ls = len(source[0]) - len(source[0].lstrip())
source = [line[ls:] for line in source]
#get rid of comments from the source
source = [item for item in source if item.lstrip()[0] != '#']
source = ''.join(source)
return source
else:
raise Exception("Expression object is not a function.")
C++ 收到这个:
Expression(somefunctogetsource)
从 c++ 如何调用表达式对象的 get_source 方法?到目前为止,我已经阅读了 python c-api 文档并尝试了这样的事情:
PyObject* baseClass = (PyObject*)expression->ob_type;
PyObject* func = PyObject_GetAttrString(baseClass, "get_source");
PyObject* result = PyObject_CallFunctionObjArgs(func, expression, NULL);
并将结果转换为字符串,但这不起作用。