小编Chr*_*ski的帖子

Pybind11 和 std::vector -- 如何使用胶囊释放数据?

我有一个返回 a 的 C++ 函数,std::vector并且使用 Pybind11,我想将该向量的内容作为 Numpy 数组返回,而不必将向量的基础数据复制到原始数据数组中。

当前尝试

这个写得很好的 SO 答案中,作者演示了如何确保在 Numpy 数组的引用计数为零时适当地释放在 C++ 中创建的原始数据数组。我尝试使用以下方法编写此版本std::vector

// aside - I made a templated version of the wrapper with which
// I create specific instances of in the PYBIND11_MODULE definitions:
//
//     m.def("my_func", &wrapper<int>, ...)
//     m.def("my_func", &wrapper<float>, ...)
// 
template <typename T>
py::array_t<T> wrapper(py::array_t<T> input) {
    auto proxy = input.template unchecked<1>();
    std::vector<T> result = compute_something_returns_vector(proxy);

    // give memory cleanup responsibility to the Numpy array …
Run Code Online (Sandbox Code Playgroud)

c++ python numpy c++11 pybind11

7
推荐指数
1
解决办法
2346
查看次数

标签 统计

c++ ×1

c++11 ×1

numpy ×1

pybind11 ×1

python ×1