I have a c++ function using eigen, which is wrapped using pybind11 so that I can call it from python. A simple version of the intended function returns an Eigen::MatrixXd
type, which pybind successfully converts to a 2D numpy array.
I would like this function to be able to return either a list or tuple of such matrices, or a 3D numpy array.
I am somewhat of a novice with c++, and the documentation for pybind does not (as far as I am able to understand) provide any direction. A mock example is below:
test.cpp
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <Eigen/Dense>
Eigen::MatrixXd test(Eigen::Ref<const Eigen::MatrixXd> x, double a)
{
Eigen::MatrixXd y;
y = x * a;
return y;
}
Eigen::MatrixXd *test2(Eigen::Ref<const Eigen::MatrixXd> x, Eigen::Ref<const Eigen::VectorXd> as)
{
Eigen::MatrixXd *ys = new Eigen::MatrixXd[as.size()];
for(unsigned int k = 0; k < as.size(); k++){
Eigen::MatrixXd& y = ys[k];
y = x * as[k];
}
return ys;
}
namespace py = pybind11;
PYBIND11_MODULE(test, m)
{
m.doc() = "minimal working example";
m.def("test", &test);
m.def("test2", &test2);
}
I would like test2
to return a list or tuple of arrays.
In python:
import test
import numpy as np
x = np.random.random((50, 50))
x = np.asfortranarray(x)
a = 0.1
a2 = np.array([1.0, 2.0, 3.0])
y = test.test(x, a)
ys = test.test2(x, a2)
The array y
is as expected, but ys
only contains the array corresponding to the first coefficient of a2
.
How should I modify test2
to correctly return more than one array? A 3D array would also be acceptable.
test
– Arias