本文介绍了如何从指针创建 n-dim numpy 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关 numpy.frombuffer 的内容,但找不到任何从指针创建数组的方法.

I've read about numpy.frombuffer, but can't find any way to create array from pointer.

推荐答案

正如上面评论中指出的,你可以使用 numpy.ctypeslib.as_array:

As pointed out in the comments above, you can use numpy.ctypeslib.as_array:

numpy.ctypeslib.as_array(obj, shape=None)

从 ctypes 数组或 ctypes POINTER 创建一个 numpy 数组.numpy 数组与 ctypes 对象共享内存.

Create a numpy array from a ctypes array or a ctypes POINTER. The numpy array shares the memory with the ctypes object.

如果从 ctypes POINTER 转换,则必须给出 size 参数.如果从 ctypes 数组转换,则忽略 size 参数

The size parameter must be given if converting from a ctypes POINTER. The size parameter is ignored if converting from a ctypes array

所以让我们模拟一个 C 函数返回一个指针并调用 malloc:

So let's mimic a C function returning a pointer with a call to malloc:

import ctypes as C
from ctypes.util import find_library
import numpy as np

SIZE = 10

libc = C.CDLL(find_library('c'))
libc.malloc.restype = C.c_void_p

# get a pointer to a block of data from malloc
data_pointer = libc.malloc(SIZE * C.sizeof(C.c_int))
data_pointer = C.cast(data_pointer,C.POINTER(C.c_int))

你现在可以让这个指针指向的数据对 numpy 可用

You can now make the data this pointer points to available to numpy

new_array = np.ctypeslib.as_array(data_pointer,shape=(SIZE,))

并证明他们正在访问相同的内存:

And to prove that they are accessing the same memory:

new_array[:] = range(SIZE)

print "Numpy array:",new_array[:SIZE]
print "Data pointer: ",data_pointer[:SIZE]

应该输出:

Numpy array: [0 1 2 3 4 5 6 7 8 9]
Data pointer:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

最后要注意的是,numpy 数组不拥有自己的内存,因此需要显式调用 free 以避免内存泄漏.

As a final note remember that the numpy array does not own its memory so explicit calls to free are required to avoid memory leaks.

del new_array
libc.free(data_pointer)

这篇关于如何从指针创建 n-dim numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 05:59