C Ext Questions

djw donald.welch at hp.com
Wed Jul 21 13:39:29 EDT 2004


Hello, I have a couple of questions about some code in a C extension module.
First, how would I convert a Python string return value from a call to
PyObject_CallFunction into a C void * buffer? Second, do I need to call
Py_XINCREF() on my callback function? (Sorry, the code is kind of
preliminary and rough)

Thanks,

Don


ext.c
-----

PyObject * callback = NULL;

PyObject * set_callback( PyObject * self, PyObject * args ) 
{
    if( !PyArg_ParseTuple( args, "O", &callback ) )
    {
        return Py_BuildValue( "i", 1 );
    }
    
    if( !PyCallable_Check( callback ))
    {
        return Py_BuildValue( "i", 2 );
    }
        
    Py_XINCREF( callback );
}

int call_callback( int param1, int param2, void * buf, int size )
{
    PyObject * result;

    if( callback )
    {
        result = PyObject_CallFunction( callback, "ii", param1, param2 );
        // Need to convert return Python string into buf....????
    }
}

PyObject * do_something( PyObject * self, PyObject * args ) 
{
    char buf[512];
    call_callback( 1, 1, (void *)&buf, sizeof(buf) );
    // buf should now contain: "This is the callback return string"
}

...


wrapper.py
----------

import ext

def f1():
    return "This is the callback return string"

ext.set_callback( f1 )
ext.do_something()

...




More information about the Python-list mailing list