首页 > 解决方案 > 返回多个 py::array 而不在 pybind11 中复制

问题描述

我正在尝试使用 pybind11 在 C++ 中构建一个 python 模块。我有以下代码:

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

struct ContainerElement
{
    uint8_t i;
    double d;
    double d2;
};

class Container
{
private:
    std::vector<uint8_t> ints;
    std::vector<double> doubles;
    std::vector<double> doubles2;

public:

    std::vector<uint8_t>& getInts() { return ints; }
    std::vector<double>& getDoubles() { return doubles; }
    std::vector<double>& getDoubles2() { return doubles2; }

    void addElement(ContainerElement element)
    {
        ints.emplace_back(element.i);
        doubles.emplace_back(element.d);
        doubles2.emplace_back(element.d2);
    }
};

void fillContainer(Container& container)
{
    for (int i = 0; i < 1e6; ++i)
    {
        container.addElement({(uint8_t)i, (double)i,(double)i });
    }
}

PYBIND11_MODULE(containerInterface, m) {
    py::class_<Container>(m, "Container")
        .def(py::init<>())
        .def("getInts", [](Container& container)
        {
            return py::array_t<uint8_t>(
                    { container.getInts().size() },
                    { sizeof(uint8_t) },
                    container.getInts().data());
        })
        .def("getDoubles", [](Container& container)
        {
            return py::array_t<double>(
                    { container.getDoubles().size() },
                    { sizeof(double) },
                    container.getDoubles().data());
        })
        .def("getDoubles2", [](Container& container)
        {
            return py::array_t<double>(
                    { container.getDoubles2().size() },
                    { sizeof(double) },
                    container.getDoubles2().data());
        });

    m.def("fillContainer", &fillContainer);
}

当我在 python 中调用这段代码时:

import containerInterface

container = containerInterface.Container()

containerInterface.fillContainer(container)

i = container.getInts()
d = container.getDoubles()
d2 = container.getDoubles2()

这可行,但是当我检查程序的内存使用情况(使用psutil.Process(os.getpid()).memory_info().rss)时,当我调用函数getInts, getDoublesgetDoubles2. 有没有办法避免这种情况?

我尝试过使用np.array(container.getInts(), copy=False),但它仍然会复制。我还尝试使用py::buffer_protocol()此处提到的 Container 类:https ://pybind11.readthedocs.io/en/stable/advanced/pycpp/numpy.html 。但是,我只能对 Ints 向量或 Doubles 向量进行此操作,而不能同时对所有向量进行操作。

PYBIND11_MODULE(containerInterface, m) {
    py::class_<Container>(m, "Container", py::buffer_protocol())
        .def(py::init<>())
        .def("getInts", &Container::getInts)
        .def("getDoubles", &Container::getDoubles)
        .def_buffer([](Container& container) -> py::buffer_info {
            return py::buffer_info(
                container.getInts().data(),
                sizeof(uint8_t),
                py::format_descriptor<uint8_t>::format(),
                1,
                { container.getInts().size() },
                { sizeof(uint8_t) * container.getInts().size() }
        );
        });
m.def("fillContainer", &fillContainer);

然后我可以使用i = np.array(container, copy=False),而无需制作副本。但是,正如我所说,它现在仅适用于Ints矢量。

标签: pythonc++pybind11

解决方案


我找到了一个可行的解决方案。虽然它可能不是最优雅的。我创建了三个新类Ints,它们采用原始容器并通过函数调用公开各自的Doubles向量。使用这三个类,我可以为所有类指定三次缓冲区协议。Doubles2getValues()

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/buffer_info.h>

namespace py = pybind11;

struct ContainerElement
{
    uint8_t i;
    double d;
    double d2;
};

class Container
{
private:
    std::vector<uint8_t> ints;
    std::vector<double> doubles;
    std::vector<double> doubles2;

public:

    std::vector<uint8_t>& getInts() { return ints; }
    std::vector<double>& getDoubles() { return doubles; }
    std::vector<double>& getDoubles2() { return doubles2; }

    void addElement(ContainerElement element)
    {
        ints.emplace_back(element.i);
        doubles.emplace_back(element.d);
        doubles2.emplace_back(element.d2);
    }
};

void fillContainer(Container& container)
{
    for (int i = 0; i < 1e6; ++i)
    {
        container.addElement({ (uint8_t)i, (double)i,(double)i });
    }
}

class Ints
{
private:
    Container& cont;
public:
    Ints(Container& cont) : cont(cont) {}
    std::vector<uint8_t>& getValues() { return cont.getInts(); }
};

class Doubles
{
private:
    Container& cont;
public:
    Doubles(Container& cont) : cont(cont) {}
    std::vector<double>& getValues() { return cont.getDoubles(); }
};

class Doubles2
{
private:
    Container& cont;
public:
    Doubles2(Container& cont) : cont(cont) {}
    std::vector<double>& getValues() { return cont.getDoubles2(); }
};

PYBIND11_MODULE(newInterface, m) {
    py::class_<Container>(m, "Container")
        .def(py::init<>());

    py::class_<Ints>(m, "Ints", py::buffer_protocol())
        .def(py::init<Container&>(), py::keep_alive<1, 2>())
        .def_buffer([](Ints& ints) -> py::buffer_info {
            return py::buffer_info(
                ints.getValues().data(),
                sizeof(uint8_t),
                py::format_descriptor<uint8_t>::format(),
                ints.getValues().size()
            );
        });

    py::class_<Doubles>(m, "Doubles", py::buffer_protocol())
        .def(py::init<Container&>(), py::keep_alive<1, 2>())
        .def_buffer([](Doubles& doubles) -> py::buffer_info {
        return py::buffer_info(
            doubles.getValues().data(),
            sizeof(double),
            py::format_descriptor<double>::format(),
            doubles.getValues().size()
            );
        });

    py::class_<Doubles2>(m, "Doubles2", py::buffer_protocol())
        .def(py::init<Container&>(), py::keep_alive<1, 2>())
        .def_buffer([](Doubles2& doubles2) -> py::buffer_info {
        return py::buffer_info(
            doubles2.getValues().data(),
            sizeof(double),
            py::format_descriptor<double>::format(),
            doubles2.getValues().size()
            );
        });

    m.def("fillContainer", &fillContainer);
}

这样我就可以在 Python 中按以下方式使用代码:

import newInterface as ci
import numpy as np

container = ci.Container()
ci.fillContainer(container)

i = np.array(ci.Ints(container), copy=False)   
d = np.array(ci.Doubles(container), copy=False)    
d2 = np.array(ci.Doubles2(container), copy=False)

一旦fillContainer填充了容器,numpy 数组的构造就不会从这个容器中复制值。


推荐阅读