将std :: vector转换为NumPy数组而不复制数据 [英] Convert a std::vector to a NumPy array without copying data
问题描述
我有一个C ++库,目前有一些方法里面返回 std :: vector
定义像
I have a C++ library which currently has some methods inside which return a std::vector
defined like
public:
const std::vector<uint32_t>& getValues() const;
我目前正在使用SWIG封装Python的整个库,这个工作进行得很好。
I'm currently working on wrapping the whole library for Python using SWIG and this is working well so far.
SWIG将此 getValues()
函数包装成函数,使其返回一个Python元组。问题是在我的Python端代码我想把它转换为NumPy数组。当然我可以这样做:
SWIG wraps this getValues()
function fine such that it returns a Python tuple. The issue is in my Python-side code I want to convert this to a NumPy array. Of course I can do this by:
my_array = np.array(my_object.getValues(), dtype='uint32')
但是这会导致原始向量中的所有条目首先通过SWIG复制到Python元组,然后再由我进入numpy数组。因为这个向量可能非常大,我宁愿避免做这两个副本,并希望有一种方法让SWIG创建一个numpy.array包装内存中的原始向量数据。
but this causes all the entries in the original vector to be first copied into a Python tuple by SWIG and then again into a numpy array by me. Since this vector could be very large, I'd rather avoid making these two copies and would like for a way to have SWIG create a numpy.array wrapper around the original vector data in memory.
我已阅读 numpy.i 的文档,但是明确提到不支持输出数组,因为它们似乎是在C风格数组而不是C ++向量的假设下工作。
I've read the documentation for numpy.i but that explicitly mentions that output arrays are not supported since they seem to be working under the assumption of C-style arrays rather than C++ vectors.
numpy.array的底层数据结构是只是一个C风格的数组作为一个C ++ std :: vector,所以我希望它是可行的,然后访问内存中的相同的数据。
numpy.array's underlying data structure is just a C-style array as is a C++ std::vector so I would hope that it is feasible to have then access the same data in memory.
有任何方法让SWIG返回一个不复制原始数据的numpy.array?
Is there any way to make SWIG return a numpy.array which doesn't copy the original data?
推荐答案
显然是 C ++向量到(C)数组,请参见有关此问题的答案:如何将向量转换为数组C ++
Apparently is is trivial to "cast" a C++ vector to (C) array, see answer on this question: How to convert vector to array C++
接下来,您可以创建一个numpy数组,使用该C数组而不复制,请参阅这里讨论: https://groups.google.com/forum/?fromgroups=#!topic/cython-users/Ubh2nG0_R9g
Next you can create a numpy array which will use that C array without copying, see discussion here: https://groups.google.com/forum/?fromgroups=#!topic/cython-users/Ubh2nG0_R9g or google for PyArray_SimpleNewFromData
.
我不希望SWIG自动为你执行所有这些操作,你应该为自己的函数 getValues
写一个包装器,比如 getValuesAsNumPyArray
。
I wouldn't expect SWIG to do all these for you automatically, instead you should probably write a wrapper for your function getValues
yourself, something like getValuesAsNumPyArray
.
这篇关于将std :: vector转换为NumPy数组而不复制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!