PyObject_CallObject: difference between functions and class methods

Hrvoje Niksic hniksic at xemacs.org
Thu Sep 27 10:15:21 EDT 2007


[ Note that there is now a mailing list dedicated to the C API:
http://mail.python.org/mailman/listinfo/capi-sig ]

mauro <mauro.tiz at gmail.com> 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 ... */

  Py_DECREF(result);
  Py_INCREF(Py_None);
  return Py_None;      /* or whatever */
}



More information about the Python-list mailing list