Why can't std::ref be used to pass objects into Boost.Python modules?

146 views Asked by At

Environment: Boost 1.61.0 compiled with Python 3.5

The following C++ code outputs 12:

class A
{
public:
    int func() { return 12; }
};

BOOST_PYTHON_MODULE(bridge)
{
    using namespace boost::python;
    class_<A>("A", no_init)
        .def("func", &A::func);
}

int main()
{
    A a;
    PyImport_AppendInittab("bridge", PyInit_bridge);
    Py_Initialize();
    using namespace boost::python;

    dict dictMain = extract<dict>(import("__main__").attr("__dict__"));

    import("bridge").attr("a") = boost::ref(a);
    exec("import bridge", dictMain);
    exec("print(bridge.a.func())", dictMain);
}

However, if I replace boost::ref with std::ref, a boost::python::error_already_set instance is thrown.

Why cannot std::ref be used here?

1

There are 1 answers

0
outoftime On BEST ANSWER

Nice article about handling python exceptions in C++. Any way I guess python through exception AttributeError because of difference in reference_wrapper implementations in std and boost libraries. You can see difference even in public interface. std::reference_wrapper has no get_pointer() method.