Here描述了PyArrayObject结构。
在Python会话中,我有以下内容:
>>> t_ar1 = np.linspace(0, 15, 16).reshape((4, 4))
>>> print(hex_fmt(string_at(id(t_ar1), 80).hex()))
0100000000000000
40b06eecbd7f0000
3053b973bf550000
02000000ffffffff
70eaa873bf550000
80eaa873bf550000
50c826adbd7f0000
00b66eecbd7f0000
01050000322c2033
0000000000000000
根据我的理解,第三行是指向数组实际数据的指针。在那里查看数据,我发现
>>> print(hex_fmt(string_at(id(0x55bf73b95330), 96).hex()))
0200000000000000
4049a801be7f0000
0200000000000000
3053b933fd560100
489601adbd7f0000
10ab27adbd7f0000
0000000000000000
0000000000000000
d09501adbd7f0000
b0aa27adbd7f0000
0000000000000000
0000000000000000
在这里,我期待在某处看到浮点数0.0 - 15.0。但是,我似乎无法找到它们。这里发生了什么?
string_at
来自ctypes
模块。
要直接从numpy数组获取数据,您需要将字节字符串(通过string_at
获得)解释为浮点数数组(8字节双精度数)。因此,我们需要使用struct module将byte-string解释为数字数组:
from ctypes import string_at
import numpy as np
import struct # needed to unpack data
t_ar1 = np.linspace(0, 15, 16).reshape((4, 4))
struct.unpack('16d', string_at(t_ar1.__array_interface__['data'][0], size=8 * 16))
(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0)
它应该是
string_at(0x55bf73b95330, 96)
而不是我拥有的,
string_at(id(0x55bf73b95330), 96)
在这种情况下,你会得到
>>> print(hex_fmt(string_at(0x55bf73b95330, 96).hex()))
0000000000000000
000000000000f03f
0000000000000040
0000000000000840
0000000000001040
0000000000001440
0000000000001840
0000000000001c40
0000000000002040
0000000000002240
0000000000002440
0000000000002640
正如所料。