Invoking a method on an object
Asked Answered
P

2

9

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")
Pascasia answered 1/9, 2009 at 19:8 Comment(0)
S
9
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.

Sybyl answered 1/9, 2009 at 19:14 Comment(1)
Knowing what "Object protocol" is was the problem. Also, I was looking for invoke for some reason. Thanks.Pascasia
G
3

Your example would be:

PyObject* ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg");
Goldin answered 1/9, 2009 at 19:27 Comment(3)
I know its 7 years too late but what does the (s) mean in the format arg.?Natalyanataniel
It's the same format string as used by Py_BuildValue: the parens means it will build a tuple, the s means the next argument ("An arg") will be a C char* string, converted to a Python string. The tuple is used as the positional arguments of the function, so we are passing one string.Goldin
What if I want to pass an c array as a list of strings or list of doubles such as, ['kks', 'sss','www','sse'] or [323.9, 32, 443, 434.8,56.6]?Trisyllable

© 2022 - 2024 — McMap. All rights reserved.