Given a PyObject* pointing to a python object, how do I invoke one of the object methods? The documentation never gives an example of this:
PyObject* obj = ....
PyObject* args = Py_BuildValue("(s)", "An arg");
PyObject* method = PyWHATGOESHERE(obj, "foo");
PyObject* ret = PyWHATGOESHERE(obj, method, args);
if (!ret) {
// check error...
}
This would be the equivalent of
>>> ret = obj.foo("An arg")
PyObject* obj = ....
PyObject *ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg");
if (!ret) {
// check error...
}
Read up on the Python C API documentation. In this case, you want the 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.
And
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.