# Start of memory.py. import ctypes as ct def addressOffset(x, offset, bt): return ct.cast(ct.addressof(x.contents)+int(offset), ct.POINTER(bt)) def allocateMem(size): return ct.cast((ct.c_byte * max(0,size))(), ct.POINTER(ct.c_byte)) # Copy an array if its is not-None. This is important for treating # Numpy arrays as flat memory, but has some overhead. def normaliseArray(x): if (x.base is x) or (x.base is None): return x else: return x.copy() def unwrapArray(x): return normaliseArray(x).ctypes.data_as(ct.POINTER(ct.c_byte)) def createArray(x, shape): # HACK: np.ctypeslib.as_array may fail if the shape contains zeroes, # for some reason. if any(map(lambda x: x == 0, shape)): return np.ndarray(shape, dtype=x._type_) else: return np.ctypeslib.as_array(x, shape=shape) def indexArray(x, offset, bt, nptype): return nptype(addressOffset(x, offset*ct.sizeof(bt), bt)[0]) def writeScalarArray(x, offset, v): ct.memmove(ct.addressof(x.contents)+int(offset)*ct.sizeof(v), ct.addressof(v), ct.sizeof(v)) # An opaque Futhark value. class opaque(object): def __init__(self, desc, *payload): self.data = payload self.desc = desc def __repr__(self): return "".format(self.desc) # End of memory.py.