#include #include #include #include #include using namespace std; #include #include #include #include #include #include using namespace boost::python; #include #include #include class B { public: B(float val) : someval(val) {} float Value() const { return someval; } void SetValue(float val) { someval = val; } protected: float someval; }; class A { public: A(B& b) : bref(b) {} B &GetB() const { return(bref); } protected: B &bref; }; BOOST_PYTHON_MODULE(example) { // Expose the State class to Python class_("B", init()) .add_property("value", &B::Value, &B::SetValue) ; class_("A", init()) .def("get_b", &A::GetB, return_internal_reference<>()) ; } const char script[] = "from example import *\n" "\n" "class C(A):\n" "\n" "\tdef dostuff(self):\n" "\t\tprint \"Hello from Python\"\n" "\t\tprint \"B Value(py): \", self.get_b().value\n" "\t\tself.get_b().value = self.get_b().value - 5.0\n" "\t\tprint \"B Value(py): \", self.get_b().value\n" "\t\tprint \"Goodbye from Python\"\n" "\n"; void main(void) { // initialize the python interpretor Py_Initialize(); // add custom module PyImport_AppendInittab("example", initexample); // obtain the __main__ namespace handle<> mMainModule = handle<>(borrowed( PyImport_AddModule("__main__") ));; handle<> mMainNamespace = handle<>(borrowed( PyModule_GetDict(mMainModule.get()) )); // evaluate the python builtins builtins handle<> mBuiltinsNamespace = handle<>(borrowed( PyEval_GetBuiltins() )); B *b = new B(10); try { // parse script node *pythonNode = PyParser_SimpleParseString(script, Py_file_input); // compile script PyCodeObject* codeObject = PyNode_CompileFlags(pythonNode, "C", NULL); // evaluate script into object object result(handle<>(PyEval_EvalCode(codeObject, mMainNamespace.get(), mMainNamespace.get()))); // get object from namespace dict main_namespace(mMainNamespace); object typeObj = main_namespace["C"]; // create new instance of object object newInstance = typeObj(*b); cout << "B Value: " << b->Value() << endl; call_method(newInstance.ptr(), "dostuff"); cout << "B Value: " << b->Value() << endl; } catch(error_already_set) { if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); } } Py_Finalize(); getch(); }