gpt4 book ai didi

python - 将 Eigen 数组从 C++ 传输到 Python 时地址发生变化

转载 作者:行者123 更新时间:2023-11-30 04:57:45 24 4
gpt4 key购买 nike

我创建了一个 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

最佳答案

修复打印地址的 C++ 行:

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

现在它正在打印内存中数组的实际地址。在不引用 data() 方法的情况下,您只是打印实际数组的 Eigen 包装器对象的地址。

关于python - 将 Eigen 数组从 C++ 传输到 Python 时地址发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51959575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com