// Copyright David Abrahams 2002. Permission to copy, use, // modify, sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. #include #include #include #include #include #include #include #include #include #include #include using namespace boost::python; typedef std::list list_int; void push_back(list_int& x, int *y) { x.push_back(y); } BOOST_PYTHON_MODULE(iterator_ext) { class_("list_int") .def("push_back", push_back) .def("__iter__", iterator()) ; } void test() { //- INITIALIZATION -----------------------------------------------------------// if (PyImport_AppendInittab("iterator_ext", inititerator_ext) == -1) throw std::runtime_error("Failed to add iterator_ext to the interpreter's " "builtin modules"); // Initialize the interpreter Py_Initialize(); // Retrieve the main module handle<> main_module( borrowed(PyImport_AddModule("__main__")) ); // Retrieve the main modules namespace handle<> main_namespace( borrowed(PyModule_GetDict(main_module.get())) ); list_int IntList; int i1 = 1; int i2 = 2; int i3 = 3; IntList.push_back(&i1); IntList.push_back(&i2); IntList.push_back(&i3); handle<> result( PyRun_String( "from iterator_ext import *\n", Py_file_input, main_namespace.get(), main_namespace.get()) ); // Result is not needed result.reset(); object globals = object(main_namespace); // borrowed(PyModule_GetDict(main_module.get()))); globals["IntList"] = &IntList; // Define the derived class in Python. // (You'll normally want to put this in a .py file.) handle<> result1( PyRun_String( "for i in IntList:\n" " print i\n", Py_file_input, main_namespace.get(), main_namespace.get()) ); // Result is not needed result1.reset(); } int main() { if (handle_exception(test)) { if (PyErr_Occurred()) PyErr_Print(); return 1; } return 0; }