3

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"?

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.