PyCFunction_New() ?

Alex Martelli aleaxit at yahoo.com
Thu Sep 16 07:52:34 EDT 2004


Scott Deerwester <scott at deerwester.org> wrote:

> Is it possible to create a Python-callable object, dynamically, in C/C++? I

Sure!  But I'm not clear on why you want to create it dynamically.  The
C++ code is there all the time, isn't it?  So why not the wrapping of it
into Python-callable terms...?

> Even better would be:
> 
> PyCFunction *MyClass::pyCallback(PyObject *ob, PyObject *args) { ... }
> 
> MyClass::MyClass()
> {
>   ...
>   PyObject_CallMethod(somePythonObject, "setCallback", this->pyCallback);
>   ...
> }

Here pyCallback _returns_ a pointer to a PyCFunction, yet you want to
SET it as the callback...?  I'm confused!  Also, PyObject_CallMethod
needs a format string as its 3rd arg, before the args 'proper' -- do you
intend to omit it?  Why?  Again, I'm confused.

> 
> Any help greatly appreciated!

You can call PyCFunction_New, passing it a first argument that's a
PyMethodDef struct pointer, and a 2nd argument that's a PyObject*
(whatever you want the C function to receive as the first argument,
self).  PyMethodDef is, of course:

struct PyMethodDef {
    char        *ml_name;
    PyCFunction  ml_meth;
    int          ml_flags;
    char        *ml_doc;
};
typedef struct PyMethodDef PyMethodDef;

What problems is this giving you...?


Alex



More information about the Python-list mailing list