提问人:Victor M 提问时间:11/13/2023 最后编辑:Victor M 更新时间:11/13/2023 访问量:102
将 C++ 矩阵传递给 Python 以用作 Numpy 数组?
Pass C++ matrix into Python to use as Numpy array?
问:
我正在用 C++ 对矩阵进行一些处理,我想将其传递给 Python 程序/函数,它应该接受 Numpy 数组形式的数据,并将某些内容传回 C++ 程序。我已经浏览了Pybind11中有关Numpy数组的文档,但是我不清楚如何在C++程序中创建缓冲区协议对象并将它们传递给Python程序,以便在C++程序本身中调用。有没有办法做到这一点?
答:
-2赞
NoName
11/13/2023
#1
下面是一个最小的示例,演示如何使用 Pybind11 将 C++ 矩阵作为 Numpy 数组传递给 Python。
C++ 代码(带有 Pybind11 的 C++ 部分)
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <vector>
namespace py = pybind11;
// Example function to pass a C++ matrix to Python
py::array_t<double> ProcessMatrix(const std::vector<std::vector<double>>& matrix) {
// Calculate the size of the matrix
size_t rows = matrix.size();
size_t cols = matrix.empty() ? 0 : matrix[0].size();
// Create a new NumPy array
py::array_t<double> result({rows, cols});
// Copy data from the C++ matrix to the NumPy array
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < cols; ++j) {
*result.mutable_data(i, j) = matrix[i][j];
}
}
return result;
}
PYBIND11_MODULE(example_module, m) {
m.doc() = "Pybind11 example plugin";
m.def("process_matrix", &ProcessMatrix, "A function which processes a matrix and returns a NumPy array");
}
Python 代码(使用 C++ 函数的 Python 部分)
import example_module
import numpy as np
def main():
# Create a sample matrix in Python
matrix = [[1.0, 2.0], [3.0, 4.0]]
# Call the C++ function and get a Numpy array
np_array = example_module.process_matrix(matrix)
# Use the numpy array in Python
print(np_array)
if __name__ == "__main__":
main()
运行代码的步骤:
编译 C++ 代码:使用 C++ 编译器和 Pybind11 将 C++ 代码编译到共享库中。例如:
c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example_module`python3-config --extension-suffix`
运行 Python 代码:只需执行 Python 脚本即可。它将导入编译的 C++ 模块,并使用该函数将 C++ 矩阵转换为 Numpy 数组。
此示例提供了一个基本框架,可以根据应用程序的特定要求进行扩展。
评论
0赞
Victor M
11/13/2023
我不想在 Python 中运行 C++ 代码,而是在 C++ 中运行 Python 代码。我想将 C++ 矩阵传递给 Python 代码段,后者接受 Numpy 数组,然后让 Python 代码段将某些内容返回给 C++ 程序。
评论
from my_module import matrix_process
np.asarray(buffer)