[C++-sig] Factory using embedded Python interpreter
Wojciech Mamrak
wmamrak at gmail.com
Sat Jul 21 17:41:45 CEST 2012
Hello list,
I am trying to create C++ objects dynamically (some kind of factory)
with use of embedded Python interpreter (i.e. eval).
Naive implementation:
namespace bp = boost::python;
bp::object main_module = ...;
bp::object main_namespace = ...;
bp::object bpo_ob = bp::eval((type+"()").c_str(), main_namespace);
Object* ob = bp::extract<Object*>(pbo_ob);
Simple eval returns bp::object, so after it goes out of scope PyDECREF
is called and finally Python's garbage collector wipes Object out.
Based on FAQ's entry:
http://www.boost.org/doc/libs/1_50_0/libs/python/doc/v2/faq.html#ownership
I set held_type to std::auto_ptr in Object definition:
BOOST_PYTHON_MODULE(MyModule) {
class_<Object, std::auto_ptr<Object>>("Object", init<>());
}
but I am not sure how to take the ownership over objects created this
way. I was thinking about:
bp::object bpo_ob = bp::eval((type+"()").c_str(), main_namespace);
std::auto_ptr<Object> ob = bp::extract<std::auto_ptr<Object>>(bpo_ob);
Object* o = ob.release();
but I am not sure about its correctness with respect to memory leaks.
When run, the program does not crash.
Thanks!
More information about the Cplusplus-sig
mailing list