0

Here describes the PyArrayObject struct.

In a Python session, I have the following:

>>> 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

From my understanding, the third line is a pointer to the actual data of the array. Viewing the data there, I find

>>> print(hex_fmt(string_at(id(0x55bf73b95330), 96).hex()))
0200000000000000
4049a801be7f0000
0200000000000000
3053b933fd560100
489601adbd7f0000
10ab27adbd7f0000
0000000000000000
0000000000000000
d09501adbd7f0000
b0aa27adbd7f0000
0000000000000000
0000000000000000

Here, I'm expecting to see the floating point numbers 0.0 - 15.0 somewhere. However, I can't seem to find them. What's going on here?

2
  • 2
    What are hex_fmt and string_at? Commented Apr 12, 2019 at 0:34
  • string_at is from the ctypes module. hex_fmt just pretty-prints the hex (it's unimportant). Commented Apr 12, 2019 at 1:41

2 Answers 2

1

string_at is from ctypes module.

To get the data directly from a numpy array you need to interpret byte-string (obtained by means of string_at) as array of floating point numbers (8-byte doubles). So, we need to use struct module to interpret byte-string as array of numbers:

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)

Sign up to request clarification or add additional context in comments.

Comments

0

It should be

string_at(0x55bf73b95330, 96)

Rather than what I had,

string_at(id(0x55bf73b95330), 96)

In this case, you'll get

>>> print(hex_fmt(string_at(0x55bf73b95330, 96).hex()))
0000000000000000
000000000000f03f
0000000000000040
0000000000000840
0000000000001040
0000000000001440
0000000000001840
0000000000001c40
0000000000002040
0000000000002240
0000000000002440
0000000000002640

As expected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.