如何使用ctypes指定Numpy数组的内存地址? [英] how can I specify the memory address of a Numpy array using ctypes?

查看:333
本文介绍了如何使用ctypes指定Numpy数组的内存地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构造一个从特定内存地址开始的Numpy数组.我该怎么做?我认为解决方案涉及ctypes,但我无法从文档中找出答案.

I would like to construct a Numpy array that starts at a specific memory address. How would I do that? I assume the solution involves ctypes but I can't figure it out from the docs.

更多详细信息和上下文

我想创建许多数组,它们的值都在顺序存储器地址上.例如,两个大小为2的数组,其中第一个数组的第一个内存地址为N,第二个数组的最后一个内存地址为N +3.我可以通过制作一个大小为4的数组并将其切片来达到相同的效果.但是,我想为每个切片"分别调用数组构造函数.我正在尝试跟踪某个C库中的错误.

I would like to create a number of arrays whose values are all at sequential memory addresses. For example, two size 2 arrays, where the 1st mem address of the 1st array is N and the last mem address of the 2nd array is N + 3. I could achieve the same affect by making one size 4 array and slicing it... but I want to call the array constructor a separate time for each "slice." I am trying to track a bug in a certain C library.

推荐答案

制作10个字节的数组:

Make an array of 10 bytes:

In [287]: x = np.arange(10, dtype=np.uint8)
In [288]: x
Out[288]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)
In [289]: x.__array_interface__
Out[289]: 
{'data': (155596184, False),
 'descr': [('', '|u1')],
 'shape': (10,),
 'strides': None,
 'typestr': '|u1',
 'version': 3}
In [290]: x.data
Out[290]: <memory at 0xaec88f34>

使用相同的数据缓冲区,但使用偏移量,使用ndarray制作另一个数组:

Make another array with ndarray, using the same data buffer, but with an offset:

In [291]: y=np.ndarray(shape=(3,), dtype=x.dtype, buffer=x.data, offset=3)
In [292]: y
Out[292]: array([3, 4, 5], dtype=uint8)
In [293]: y.__array_interface__
Out[293]: 
{'data': (155596187, False),
 'descr': [('', '|u1')],
 'shape': (3,),
 'strides': None,
 'typestr': '|u1',
 'version': 3}

这看起来与3个元素的切片相同:

this looks the same as a 3 element slice:

In [294]: z=x[3:6]
In [295]: z
Out[295]: array([3, 4, 5], dtype=uint8)
In [296]: z.__array_interface__
Out[296]: 
{'data': (155596187, False),
 'descr': [('', '|u1')],
 'shape': (3,),
 'strides': None,
 'typestr': '|u1',
 'version': 3}

如果我对指定内存地址有更多了解,我可能只需使用buffer参数即可,默认值为0 offset.但是从您添加的内容来看,offset的使用可能正是您想要的.

If I knew more about specifying a memory address I probably could get by with just the buffer parameter, and default 0 offset. But from your additions, the use of offset might be just what you want.

这篇关于如何使用ctypes指定Numpy数组的内存地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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