-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmemory_descriptors.py
More file actions
41 lines (31 loc) · 1.11 KB
/
Copy pathmemory_descriptors.py
File metadata and controls
41 lines (31 loc) · 1.11 KB
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
import ctypes
from typing import Any
import numpy.typing as npt
def build_struct(ty_ptr, intptr_t, N) -> type[ctypes.Structure]:
"""
Build a ctypes structure for a NumPy array of a given element type.
"""
class MemRefDescriptor(ctypes.Structure):
_fields_ = [
("allocated", ty_ptr),
("aligned", ty_ptr),
("offset", intptr_t),
("sizes", intptr_t * N),
("strides", intptr_t * N),
]
return MemRefDescriptor
def as_memref_descriptor(arr: npt.NDArray[Any], ty: type[Any]) -> ctypes.Structure:
"""
Convert a numpy array to a memref descriptor
"""
N = arr.ndim
ty_ptr = ctypes.POINTER(ty)
intptr_t = getattr(ctypes, f"c_int{8 * ctypes.sizeof(ctypes.c_void_p)}")
struct_constructor = build_struct(ty_ptr, intptr_t, N)
allocated = ctypes.cast(arr.ctypes.data, ty_ptr)
aligned = allocated
offset = intptr_t(0)
sizes = (intptr_t * N)(*arr.shape)
strides = (intptr_t * N)(*arr.strides)
# Return the memref descriptor
return struct_constructor(allocated, aligned, offset, sizes, strides)