给定一个指向 python 对象的 PyObject*,我如何调用其中一个对象方法?文档从未给出这样的例子:
PyObject* obj = ....
PyObject* args = Py_BuildValue("(s)", "An arg");
PyObject* method = PyWHATGOESHERE(obj, "foo");
PyObject* ret = PyWHATGOESHERE(obj, method, args);
if (!ret) {
// check error...
}
这相当于
>>> ret = obj.foo("An arg")
最佳答案
PyObject* obj = ....
PyObject *ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg");
if (!ret) {
// check error...
}
阅读 Python C API documentation .在这种情况下,您需要 object protocol .
PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...)
Return value: New reference.
Call the method named method of object o with a variable number of C arguments. The C arguments are described by a
Py_BuildValue()
format string that should produce a tuple. The format may beNULL
, indicating that no arguments are provided. Returns the result of the call on success, orNULL
on failure. This is the equivalent of the Python expressiono.method(args)
. Note that if you only passPyObject * args
,PyObject_CallMethodObjArgs()
is a faster alternative.
和
PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL)
Return value: New reference.
Calls a method of the object
o
, where the name of the method is given as a Python string object in name. It is called with a variable number ofPyObject*
arguments. The arguments are provided as a variable number of parameters followed byNULL
. Returns the result of the call on success, orNULL
on failure.
关于python - 在对象上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1364117/