Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.