Pybind11 - 返回指向 unique_ptr 容器的指针

标签 pybind11

我一直在使用优秀的 pybind11 库,但遇到了困难。 我需要向 Python 返回一个指向不可复制对象的指针(因为该对象包含 unique_ptrs)。

一般来说,这在使用 return_value_policy::reference 的警告下工作得很好。 但是,返回指向具有不可复制向量的对象的指针会导致编译错误。 在这种情况下,pybind 似乎想要执行复制,即使返回值策略是引用并且函数显式返回一个指针。

这是为什么?有解决方法吗?

我使用的是 VS2017 15.9.2 和最新的 pybind11 off master

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
#include <memory>

/* This fails to compile... */
struct myclass
{
    std::vector<std::unique_ptr<int>> numbers;
};

/* ...but this works
struct myclass
{
    std::unique_ptr<int> number;
};
*/

void test(py::module &m)
{
    py::class_<myclass> pymy(m, "myclass");

    pymy.def_static("make", []() {
        myclass *m = new myclass;
        return m;
    }, py::return_value_policy::reference);
}

最佳答案

我解决了这个问题

需要显式删除复制构造函数和赋值运算符,即添加以下内容可以让 pybind 认识到它无法进行复制

myclass() = default;
myclass(const myclass &m) = delete;
myclass & operator= (const myclass &) = delete;

关于Pybind11 - 返回指向 unique_ptr 容器的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807248/

相关文章:

python - pybind11::dict 中的 pybind11::对象

python - Pybind11 函数调用阻塞主线程

c++ - `overload_cast` 在特定情况下失败

python - 通过 pybind11 返回 numpy 数组

python - 使用 pybind11 嵌入 python。虚拟环境不行

Python 和 C++ : How to use pybind11 with Cmakelists including GSL libraries

c++ - 如何 static_cast 一个指向 const 成员函数的指针?

python - 简单的 pybind11 模块失败,没有命名模块

python - 将 pybind11 绑定(bind)标记为已弃用的最佳方法

ubuntu-16.04 - 如何安装python-pybind11?