|
Re: instantiating python objects within C++: msg#00193python.c++
Hi Adam, Adam Hupp wrote: Try looking at libs/python/test/embedding.cpp. It has a nice example thanks for the pointer. I looked, but the main question is still unanswered, as the example instantiates an object 'implemented' in python (derived from a C++ type). Do I really have to run the interpreter to instantiate a python-wrapper-object around my own type ? Anyways, I tried and failed. I attach the test, may be someone can see what I'm doing wrong... Running the compiled program (which calls 'script.py') results in the following output: <code object ? at 0x8120068, file "null", line 1> <type 'code'> python exception Traceback (most recent call last): File "script.py", line 3, in ? object.value = 42 TypeError: 'code' object has only read-only attributes (assign to .value) Thanks a lot, Stefan #include <boost/python.hpp> #include <boost/python/extract.hpp> #include <boost/python/dict.hpp> #include <boost/python/class.hpp> #include <iostream> #include <fstream> #include <sstream> #include <memory> #include <string> class Foo { public: Foo() : mValue(0) {} void SetValue(int i) { mValue = i;} int GetValue() const { return mValue;} private: int mValue; }; namespace python = boost::python; BOOST_PYTHON_MODULE(Sandbox) { python::class_<Foo> foo("Foo"); foo.add_property("value", &Foo::GetValue, &Foo::SetValue); } int main(int, char **) { PyImport_AppendInittab("Sandbox", initSandbox); Py_Initialize(); python::handle<> main_module(python::borrowed(PyImport_AddModule("__main__"))); python::dict main_namespace = python::dict(python::handle<>(python::borrowed(PyModule_GetDict(main_module.get())))); try { python::handle<> FooType(Py_CompileString("from Sandbox import * \n" "Foo \n", "null", Py_file_input)); python::object foo(FooType); main_namespace["object"] = foo; FILE *fp = fopen("script.py", "r"); python::handle<> result(PyRun_File(fp, "script.py", Py_file_input, main_namespace.ptr(), main_namespace.ptr())); Foo &foo1 = python::extract<Foo &>(main_namespace["object"]); std::cout << foo1.GetValue() << std::endl; } catch(const python::error_already_set &) { std::cout << "python exception" << std::endl; PyErr_Print(); } Py_Finalize(); } print object print type(object) object.value = 42 |
|
| <Prev in Thread] | Current Thread | [Next in Thread> |
|---|---|---|
| Previous by Date: | Re: Can't get a simple example with fstream to compile & link: 00193, Ralf W. Grosse-Kunstleve |
|---|---|
| Next by Date: | Automatic (implicit ?) type conversion for a data member of a struct.: 00193, pj |
| Previous by Thread: | Re: instantiating python objects within C++i: 00193, Adam Hupp |
| Next by Thread: | Re: instantiating python objects within C++: 00193, Gavin Doughtie |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |