From: Barry S. <ba...@ba...> - 2006-12-03 19:33:43
|
On Dec 1, 2006, at 18:54, carlos choy wrote: > I am thinking of using PyCXX principally for embedding Python. This works. You will need to create a module using PyCXX if you wish the python code to be able to call you back. If you use threads there is extra work in the init and in the module you will need to worry about. > Here is some > basic code for embedding that I intend to use: > > **************************************************************** > #include <Python.h> > > int main(int argc, char *argv[]) > { > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > Use appropriate Py:: objects. > if (argc < 3) > { > printf("Usage: exe_name python_source function_name\n"); > return 1; > } > Give python an argc and argv before calling init. > // Initialize the Python Interpreter > Py_Initialize(); > > // Build the name object > pName = PyString_FromString(argv[1]); Py::String name( argv[1] ); > > // Load the module object > pModule = PyImport_Import(pName); Py::Module module( PyImport_Import( name ) ); > // pDict is a borrowed reference > pDict = PyModule_GetDict(pModule); Py::Dict dict( module.getDict() ); > > // pFunc is also a borrowed reference > pFunc = PyDict_GetItemString(pDict, argv[2]); Py::Callable func( dict[ Py::String( argv[2] ) ] ); > > if (PyCallable_Check(pFunc)) > { > PyObject_CallObject(pFunc, NULL); > } else > { > PyErr_Print(); > } No need to do the if an exception will be raise if an objects type does not match. // no args Py::Tuple args( 0 ); func.apply( args ); > // Clean up > Py_DECREF(pModule); > Py_DECREF(pName); No need to call dec. But you will need to make sure that the Py:: onjects go out of scope so that they are deleted before calling finalize. > > // Finish the Python Interpreter > Py_Finalize(); > > return 0; > } > ********************** > > I assume the above will work. Is there a more PyCXX way of doing > this? See comments in line above. > > Lastly, I need to have callbacks into C++ code from Python. The > Callable > interface is documented, but samples. Can someone please post > examples of > how to use it? > > _________________________________________________________________ Define a module and add functions and classes. Look at the example that comes with PyCXX in the Demo folder. For example look at range.hxx and .cxx. If you want a full scale example look at the source of the Python SVN extension, pysvn at http://pysvn.tigris.org - download a source kit add you will see examples of calling C++ from python and calling python from C++. Barry |