首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在pybind11 & c++中通过引用传递向量

如何在pybind11 & c++中通过引用传递向量
EN

Stack Overflow用户
提问于 2021-11-17 22:18:44
回答 1查看 1.9K关注 0票数 2

我尝试通过引用将向量/数组从python通过pybind11传递到C++库。C++库可以填写数据。在调用C++之后,我希望python端能够得到数据。

以下是简化的C++代码:

代码语言:javascript
复制
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>

class Setup
{
public:
    Setup(int version) : _version(version) {}
    int _version;
};

class Calculator
{
public:
    Calculator() {}
    static void calc(const Setup& setup, std::vector<double>& results) { ... }
}

namespace py = pybind11;

PYBIND11_MODULE(one_calculator, m) {
    // optional module docstring
    m.doc() = "pybind11 one_calculator plugin";

    py::class_<Setup>(m, "Setup")
        .def(py::init<int>());

    py::class_<Calculator>(m, "Calculator")
        .def(py::init<>())
        .def("calc", &Calculator::calc);
}

在python方面,我打算:

代码语言:javascript
复制
import os
import sys
import numpy as np
import pandas as pd
sys.path.append(os.path.realpath('...'))
from one_calculator import Setup, Calculator

a_setup = Setup(1)
a_calculator = Calculator()

results = []
a_calculator.calc(a_setup, results)

results

显然结果没有被传回。有什么好办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-30 15:05:54

想出了一个办法:

代码语言:javascript
复制
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>

#include "Calculator.h" // where run_calculator is

namespace py = pybind11;

// wrap c++ function with Numpy array IO
int wrapper(const std::string& input_file, py::array_t<double>& in_results) {
    if (in_results.ndim() != 2)
        throw std::runtime_error("Results should be a 2-D Numpy array");

    auto buf = in_results.request();
    double* ptr = (double*)buf.ptr;

    size_t N = in_results.shape()[0];
    size_t M = in_results.shape()[1];

    std::vector<std::vector<double> > results;

    run_calculator(input_file, results);

    size_t pos = 0;
    for (size_t i = 0; i < results.size(); i++) {
        const std::vector<double>& line_data = results[i];
        for (size_t j = 0; j < line_data.size(); j++) {
            ptr[pos] = line_data[j];
            pos++;
        }
    }
}

PYBIND11_MODULE(calculator, m) {
    // optional module docstring
    m.doc() = "pybind11 calculator plugin";

    m.def("run_calculator", &wrapper, "Run the calculator");
}

Python侧

代码语言:javascript
复制
results= np.zeros((N, M))
run_calculator(input_file, results)

这样,我也不会向python端公开类、安装程序和计算器。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70012280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档