R zu
R zu

Reputation: 2074

Address changes upon transferring Eigen array from c++ to python

I make a c++ function to create numpy arrays with the correct memory alignment.

Somehow, python and c++ print two different addresses for the "same" array.

Does that means pybind11 still copy the array?

If that is the case, how to avoid copying?

The pybind11 is from: https://github.com/pybind/pybind11/archive/stable.zip

c++ code:

#include <Eigen/Eigen>
#include <iostream>
#include <pybind11/eigen.h>

template <typename T>
inline Array<T, Dynamic, Dynamic>* eigen_empty(Index rows, Index cols) {
    auto a = new Array<T, Dynamic, Dynamic>(rows, cols);
    std::cout << "Address: " << (long long) a << "\n";
    return a;
}

namespace py = pybind11;

PYBIND11_MODULE(_cxx, m) {
    m.def("eigen_empty_d", &eigen_empty<double>,
          py::return_value_policy::take_ownership);
}  // python would "take_ownership" of the array

python test:

>>> x=eigen_empty_d(10,1);x.__array_interface__['data'][0];x.flags.owndata
Address: 32962272  # address printed by c++
29726560           # address from python
False              # numpy does not own the data
>>> x=eigen_empty_d(10,1);x.__array_interface__['data'][0];x.flags.owndata
Address: 32962240
29511904
False
>>> x=eigen_empty_d(10,1);x.__array_interface__['data'][0];x.flags.owndata
Address: 29516656
29726560
False
>>> x=eigen_empty_d(10,1);x.__array_interface__['data'][0];x.flags.owndata
Address: 33209440
29726560
False
>>> x=eigen_empty_d(10,1);x.__array_interface__['data'][0];x.flags.owndata
Address: 29429712
29511904
False

Upvotes: 2

Views: 205

Answers (1)

Geezer
Geezer

Reputation: 5720

Fix the C++ line printing the address to this:

std::cout << "Address: " << (long long) a->data() << "\n";

Now it's printing the actual address of the array in memory. Without referring to the data() method you're just printing the address of the Eigen wrapper object of the actual array.

Upvotes: 1

Related Questions