首页 > 解决方案 > Pybind11 和为 lambda 推导出的不一致类型

问题描述

在我无法修改的 cpp 代码中,我们有自定义类和自定义指针。此类读取一个对象,并且根据 kwargs 也可能写入它。我需要为它制作 pybind11 绑定。

根据传递的参数,我们得到指向类的 const 或非 const 指针。Pybind 抱怨 lambda 返回类型的类型不一致。init()对于制作仅适用于 const 或非 const 对象的函数来说,这一切都很顺利。不幸的是,需要同时支持这两种情况。在这种情况下,将 python 绑定到 cpp 代码的最佳方法是什么?

错误

In lambda function:
error: inconsistent types 'std::shared_ptr<myClass>' and 'std::shared_ptr<const myClass>'
deduced for lambda return type
  return *const_p;

如何修改下面的代码以支持这两种情况?使用 Cpp 11 编译器。

// those defined elsewhere
typedef std::shared_ptr< myClass > my_ptr;
typedef std::shared_ptr< const myClass > const_my_ptr;

//init function for pybind11
.def(py::init([](py::kwargs kwargs) {
    bool object_writable = py::bool_(kwargs["rw"]);
    int cache = py::bool_(kwargs["cache"]);
    std::string path = py::str(kwargs["path"]);
    if (object_writable){
        //returns non const
        my_ptr p = myClass::read_write(path)
        return *p;
    }
    else{
        //returns const
        const_my_ptr const_p = myClass::read(path, cache)
        return *const_p;
    }
}))

标签: pythonc++lambdapybind11

解决方案


推荐阅读