-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc_wrapper.py
More file actions
108 lines (82 loc) · 2.06 KB
/
c_wrapper.py
File metadata and controls
108 lines (82 loc) · 2.06 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import ctypes
import numpy as np
from pathlib import Path
# loading the shared library
LIB_PATH = Path(__file__).parent / "libfoo.so"
SHARED_LIB = ctypes.CDLL(LIB_PATH)
# structure wrappers
class Cpx(ctypes.Structure):
""" Wrapper to the c cpx structure. """
_fields_ = [
("r", ctypes.c_float),
("i", ctypes.c_float),
]
def __str__(self,) -> str:
return f"{self.r} - {self.i}"
# setting up the types
def setup_types(lib):
lib.summing.argtypes = (ctypes.c_int, ctypes.c_int)
lib.summing.restype = ctypes.c_int
lib.sum_vectors.argtypes = (
np.ctypeslib.ndpointer(dtype=int, ndim=1),
np.ctypeslib.ndpointer(dtype=int, ndim=1),
ctypes.c_int
)
lib.sum_cpx.argtypes = (Cpx, Cpx)
lib.sum_cpx.restype = Cpx
setup_types(SHARED_LIB)
def summing(x: int, y: int) -> int:
""" Sums two integer numbers.
Parameters
----------
x : int
First number.
y : int
Second number.
Returns
-------
int
Sum of x and y.
"""
return SHARED_LIB.summing(x, y)
def sum_vectors(x: np.ndarray, y: np.ndarray) -> np.ndarray:
"""
Sums the vector y into x.
Parameters
----------
x : np.ndarray
Accumulator vector of shape (n).
y : np.ndarray
Vector summed to x of shape (n)
Returns
-------
np.ndarray
Return x after y is summed to it.
"""
assert x.shape[0] == y.shape[0], "x and y must have the same length"
# lenght of the vectors
n = x.shape[0]
SHARED_LIB.sum_vectors(x, y, n)
return x
def sum_cpx(x:Cpx, y:Cpx)->Cpx:
"""
Summs two complex numbers.
Parameters
----------
x : Cpx
First complex number.
y : Cpx
Second complex number.
Returns
-------
Cpx
Sum of x and y.
"""
return SHARED_LIB.sum_cpx(x,y)
if __name__ == "__main__":
print(summing(10, 32))
print(sum_vectors(
np.array([1, 2, 3]).astype(int), # x
np.array([4, 5, 6]).astype(int) # y
))
print(sum_cpx(Cpx(1,2), Cpx(3,4)))