如何从指针创建n-dim numpy数组? [英] How to create n-dim numpy array from a pointer?

查看:142
本文介绍了如何从指针创建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)

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数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆