将Eigen数组从C ++传输到python后的地址更改

时间:2018-08-22 03:44:56

标签: python c++ numpy pybind11

我使用c ++函数创建具有正确内存对齐方式的numpy数组。

以某种方式,python和c ++为“相同”数组打印两个不同的地址。

这是否意味着pybind11仍在复制数组?

如果是这种情况,如何避免复制?

pybind11来自:https://github.com/pybind/pybind11/archive/stable.zip

c ++代码:

#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测试:

>>> 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

1 个答案:

答案 0 :(得分:1)

修复C ++行将地址打印到该行:

df = pd.concat(all_data, axis=1)

现在,它正在打印内存中数组的实际地址。不参考std::cout << "Address: " << (long long) a->data() << "\n"; 方法,您只是打印实际数组的Eigen包装对象的地址。