PyObject_CallObject: difference between functions and class methods

Hrvoje Niksic hniksic at
Thu Sep 27 16:15:21 CEST 2007

[ Note that there is now a mailing list dedicated to the C API: ]

mauro <mauro.tiz at> writes:

> I am trying to call within a C extension a Python function provided as
> an argument by the user with: PyObject_Call(). The C extension should
> work also if the user supplies a class method, but in this case I am
> getting an error. Do I need to explicitly pass 'self' as an argument
> to PyObject_Call()?

You don't.  The reference to self will be added automatically when
invoking the function you receive as object.method.

> if ((tmp_args = PyTuple_New(1)) == NULL)
> 		PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-
> pointer" );
> PyTuple_SetItem(tmp_args, 0, paramlist);

Maybe you are mismanaging the reference count -- PyTuple_SetItem
steals the refcount of its argument.  Anyway, why not use
PyObject_CallFunction or PyObject_CallFunctionObjArgs?  For example:

PyObject *
mymodule_main(PyObject *ignored, PyObject *func)
  PyObject *result, *my_param;
  /* ... do something, e.g. create my_param ... */

  /* call func */
  result = PyObject_CallFunction(received_func, "O", my_param);
  Py_DECREF(my_param);  /* assuming you no longer need it */
  if (!result)
    return NULL;

  /* ... do something with result ... */

  return Py_None;      /* or whatever */

More information about the Python-list mailing list