我想在 C++ 类中创建数据的 numpy 视图。
但是下面的内容是复制而不是视图。
蟒蛇测试:
import _cpp
a = _cpp.A()
print(a)
a.view()[:] = 100 # should make it all 100.
print(a)
结果:
40028064 0 0 0 // Fail: Modifying a.mutable_data() in C++ doesn't
// change _data[4]
40028064 0 0 0 // Fail: Modifying a.view() in Python 3 doesn't
// change data in a
C++ 行a.mutable_data()[0] = -100;
不会将第 0 个元素更改为 -100。这显示py::array_t<int> a(4, &_data[0]);
创建副本而不是视图int _data[4];
修改数组a.view()
不会将数据更改a
为 100 秒。这表明这a.view()
是一个副本,而不是 中数据的视图a
。
主.cpp:
#include <iostream>
#include "pybind11/pybind11.h"
#include "pybind11/numpy.h"
namespace py = pybind11;
class A {
public:
A() {}
std::string str() {
std::stringstream o;
for (int i = 0; i < 4; ++i) o << _data[i] << " ";
return o.str();
}
py::array view() {
py::array_t<int> a(4, &_data[0]);
a.mutable_data()[0] = -100;
return a;
}
int _data[4];
};
PYBIND11_MODULE(_cpp, m) {
py::class_<A>(m, "A")
.def(py::init<>())
.def("__str__", &A::str)
.def("view", &A::view, py::return_value_policy::automatic_reference);
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.9)
project(test_pybind11)
set(CMAKE_CXX_STANDARD 11)
# Find packages.
set(PYTHON_VERSION 3)
find_package( PythonInterp ${PYTHON_VERSION} REQUIRED )
find_package( PythonLibs ${PYTHON_VERSION} REQUIRED )
# Download pybind11
set(pybind11_url https://github.com/pybind/pybind11/archive/stable.zip)
set(downloaded_file ${CMAKE_BINARY_DIR}/pybind11-stable.zip)
file(DOWNLOAD ${pybind11_url} ${downloaded_file})
execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzf ${downloaded_file}
SHOW_PROGRESS)
file(REMOVE ${downloaded_file})
set(pybind11_dir ${CMAKE_BINARY_DIR}/pybind11-stable)
add_subdirectory(${pybind11_dir})
include_directories(${pybind11_dir}/include)
# Make python module
pybind11_add_module(_cpp main.cpp)