C Ext Questions

Pete Shinners pete at shinners.org
Thu Jul 22 16:51:36 CEST 2004


> 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 );
> }

You are increasing the refcount here, but before you assign a new 
callback, you will want to decrease the reference to the old callback. 
Your other problem is that if PyArg_ParseTuple fails, it is raising an 
exception. Your function _must_ return NULL or clear the exception. 
Better to return NULL and let the exception get raised.


> 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....????
>     }
> }

You will need to get a char* pointer and copy that into your buffer.
	char * str;
	str = PyString_AsString(result);
	if(!str)
	{
		Py_XDECREF(result);
		return NULL;
	}
	strncpy((char*)buf, str, size-1);
         ((char*)buf)[size-1] = 0;
	Py_DECREF(result);
	return 1;


One last warning, if your program involves multiple threads, make sure 
the Python callback only gets called from the primary thread. You'll 
have a lot of "non-beginner" work to do to safely call the Python 
callback from any thread. Anyways, this is probably not an issue.




More information about the Python-list mailing list