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")
Invoke(Object, Object[]) Invokes the method or constructor represented by the current instance, using the specified parameters.
You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.
To "invoke" appears to mean to call a method indirectly through an intermediary mechanism.
Invoke(Object, Object[]) has the following parameters. obj - The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.
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.
Your example would be:
PyObject* ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With