Передача и возврат numpy массивов в C ++ с pybind11 - PullRequest
0 голосов
/ 05 марта 2020

У меня есть python функция с именем add_array в numpyfuncs.py, которая выглядит следующим образом:

import numpy as np

def add_arrays(a, b):
    return np.add(a, b)

if __name__ == "__main__":
    data1 = np.random.random_sample((3, 2))
    data2 = np.random.random_sample((3, 2))
    print(add_arrays(data1, data2))

Я хочу вызвать эту функцию через C ++ с помощью pybind11. Так что в основном я хочу передать собственную матрицу C ++, сделать дополнение и вернуть numpy .ndarray в C ++ и снова привести его в собственную матрицу, см. Пример (который выдает мне эту ошибку:

terminate called after throwing an instance of 'pybind11::cast_error'
  what():  make_tuple(): unable to convert argument of type 'Eigen::Matrix<double, 2, 2, 0, 2, 2>' to Python object
Aborted

) ниже (main.cpp):

// Embeding the interpreter into c++
// https://pybind11.readthedocs.io/en/master/advanced/embedding.html

#include <pybind11/embed.h>
#include <iostream>
#include <string>
#include <eigen3/Eigen/Dense>

// Define namespace for pybind11
namespace py = pybind11;
using namespace pybind11::literals;


int main() {
    // Initialize the python interpreter
    py::scoped_interpreter python;

    // Import all the functions from scripts by file name in the working directory
    py::module numpyfunc = py::module::import("numpyfuncs");

    // Initialize matrices
    Eigen::Matrix2d a;
    a << 1, 2,
        3, 4;
    Eigen::MatrixXd b(2,2);
    b << 2, 3,
        1, 4;

    // Call the python function
    py::object result = numpyfunc.attr("add_arrays")(a, b);

    // Make a casting from python objects to real C++ Eigen Matrix type
    Eigen::MatrixXd c = result.cast<Eigen::MatrixXd>();

    return 0;
}

Возможно ли это? Я прочитал эту отличную документацию по Eigen и numpy, но я не могу заставить ее работать в моем примере. Что я делаю неправильно? Любая помощь будет оценена. Заранее спасибо за советы, советы и решения.

PS: Вот мой CMakeLists.txt для тестирования и компиляции:

cmake_minimum_required(VERSION 3.0)
project(numpytest)
add_subdirectory(pybind11)
file(COPY numpyfuncs.py DESTINATION .)
add_executable(numpytest main.cpp)
target_link_libraries(numpytest pybind11::embed)
...