Question

I currently have the following:

namespace py=boost::python;

//C++
void f() {
    std::cout << "hello world\n";
}

//I am not precious about this, if it can be done without a module that would be great
BOOST_PYTHON_MODULE(test)
{
    py::def("f", f);
}

int main() {
    auto main_module    =py::import("__main__");
    auto main_namespace =main_module.attr("__dict__");
    //???????
    auto result=py::exec_file("t.py", main_namespace);
}

//t.py
f()

I am trying to call f, but I am not sure of the glue required to get it to work. With classes I can do

 int main() {
     //...

     py::obejct p_my_type=py::class_<my_type>("my_type").def("f", &my_type::f);
     main_namespace["my_type"]=p_my_type;

     //...

however boost::python::def doesn't appear to return a boost::python::object like class_ does

My questions are, how do I get the first test case to work as expected? And secondly is the way in which I am exposing my types in the second code snippet "correct"?

Était-ce utile?

La solution

The fix was simple but wasn't mentioned in the doc on this page:

http://www.boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/python/embedding.html

I needed to do this:

auto main_module    =py::import("__main__");
auto main_namespace =main_module.attr("__dict__");
inittest();
auto result=py::exec_file("t.py", main_namespace);


from test import f
f()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top