Skip to content Skip to sidebar Skip to footer

How Do I Import A Class In A .py File From C++ Using Boost/python?

EDIT : Looks like I've messed up the solution from the second post, but it's still giving me an error after I corrected it. Edit : I tried importing using a full path but it gave m

Solution 1:

I figured out a workaround: since Python modules are also PyObjects, I can load the module in Python and pass it to C++ as a variable. Here's the code:

The C++ file:

boost::python::object mod;
void set_global(boost::python::object foo_module){
    mod = foo_module;
    // this is for testing
    boost::python::object test = mod.attr("Foo")(new A(1,1,1), NULL, 12);
    A* a = extract<A*>(test.attr("_A")) ;
    cout << a->_x << endl << a->_y << endl << a->_z << endl;
}

In python (from this answer) :

from .utilitiesimport foo as foo_module
set_globals(foo_module)

output:

1
1
1

Post a Comment for "How Do I Import A Class In A .py File From C++ Using Boost/python?"