@SnoopJeDi/

WellinformedHauntingGoal

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import numpy as np
import ctypes

def addr(arr):
  """ Get address of numpy array's data """
  return arr.__array_interface__['data'][0]

def summ(arr, header=''):
  """ Summarize the state of an array """
  print(header + f' (0x{addr(arr):x})')
  print(f"{' '.join(str(arr).split())}\n")

dtype = 'i4'
sz = np.nbytes[dtype]
N = 10
origarray = np.random.randint(0, 16, size=N, dtype=dtype)
viewarray = origarray.view()
cparray = origarray.copy()

summ(origarray, 'original array:')
summ(viewarray, 'view over original array:')
summ(cparray, 'copied array:')

print("------------------------")

newdata = (ctypes.c_int32*N)(*range(N))
print(f'new data (c_int32 array, N={N}):\t(0x{ctypes.addressof(newdata):x})')
newarr = np.empty(shape=(N,), dtype=dtype)
summ(newarr, 'new, unitialized array')
newarr.data = newdata
summ(newarr, 'newarr after setting newarr.data')

# frombuffer() is an even more concise way to do this, and it supports offsets!
halfarr = np.frombuffer(newdata, offset=sz*N//2, dtype=dtype)
summ(halfarr, "halfarr")

# of course, possibly silly things like reinterpreting the bytes can be done, too
watarr = np.frombuffer(newdata, dtype='i8')
summ(watarr, "watarr")

newdata[:] = [-1]*N

print("------------after modifying underlying memory------------")
summ(newarr, 'newarr')
summ(halfarr, 'halfarr')
summ(watarr, 'watarr')

newdata[:] = np.random.randint(16**2, size=N)

# we can even do Evil Things™ like memcpy()!
ctypes.memmove(addr(origarray), addr(newarr), origarray.nbytes//2)

print('------------after randomization and memmove()------------')
summ(newarr, 'newarr')
summ(origarray, 'origarray')
summ(viewarray, 'viewarray')
summ(cparray, 'cparray')