为什么 std::ref 不能用于将对象传递到 Boost.Python 模块中?

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

本文关键字:Boost Python 模块 对象 ref std 不能 用于 为什么      更新时间:2023-10-16

环境:Boost 1.61.0使用Python 3.5编译

以下c++代码输出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);
}

但是,如果我将boost::ref替换为std::ref,则抛出boost::python::error_already_set实例。

为什么这里不能使用std::ref ?

关于在c++中处理python异常的好文章。无论如何,我猜python通过异常AttributeError,因为reference_wrapper在std和boost库中的实现不同。即使在公共界面上也可以看到差异。std::reference_wrapper没有get_pointer()方法