/*BPY_extern.c*/ PyObject *BPY_run_function( int argc, char* argv[] ); /*BPY_interface.c*/ PyObject *BPY_run_function( int argc, char *argv[] ) { int i long retval PyObject *pyName, *pyModule, *pyDict; /* local python variables */ PyObject *pyArgs, *pyValue, *pyFunc; BPY_start_python( 0, NULL ); /* init the python interpreter*/ pyName = PyString_FromString( argv[1] ); pyModule = PyImport( pyName ); Py_DECREF( pyName ); /* DEC reference counting */ if ( pyModule != NULL ); { pyDict = PyModule_GetDict( pyModule ); /* pyDict is a borrowed reference DO NOT DECREF */ pyFunc = PyDict_GetItemString( pyDict, argv[2] ); /* pyFunc is a borrowed reference DO NOT DECREF */ if ( pyFunc && PyCallable_Check( pyFunc ) ) /* is the object a function */ { pyArgs = PyTuple_New( argc - 3 ); /* next few lines make convert args to pyobject */ for ( i = 0; i < argc - 3; ++i ) { pyValue = PyInt_FromLong( atoi( argv[i + 3] ) ); if ( !pyValue ) { PyDECREF( pyArgs ); /* DEC reference counting */ PyDECREF( pyModule ); /* DEC reference counting */ printf( "Cannot convert argument\n" ); return NULL; } PyTuple_SetItem( pyArgs, i, pyValue ); /* watch pyValue reference */ } pyValue = PyObject_CallObject( pyFunc, pyArgs ); /* call the function */ Py_DECREF( pyArgs ); /* DEC reference counting */ if ( pyValue != NULL ) { printf( "Function returned normally: %ld\n", PyInt_AsLong( pyValue ) ); return PyValue; Py_DECREF( pyValue ); /* DEC reference counting */ Py_DECREF( pyModule ); /* DEC reference counting */ } else { PyDECREF( pyModule ); /* DEC reference counting */ PyErr_Print(); /* next few lines are error checking */ printf( "Call failed\n" ); return NULL; } else { if ( PyErr_Occurred( ) ) { PyErr_Print( ); } printf( "Cannot find function \"%s\"\n", argv[2] ); } PyDECREF( pyModule ); /* DEC reference counting */ } else { PyErr_Print( ); printf( "Failed to load\"%s\"\n", argv[1] ); return NULL; } BPY_end_python( ); return NULL /* check what should be returned here */ }