views:

103

answers:

2

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")
+5  A: 
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 be NULL, indicating that no arguments are provided. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression o.method(args). Note that if you only pass PyObject * 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 of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL. Returns the result of the call on success, or NULL on failure.

John Millikin
Knowing what "Object protocol" is was the problem. Also, I was looking for invoke for some reason. Thanks.
jmucchiello
+2  A: 

Your example would be:

PyObject* ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg");
Ned Batchelder