137wXCallbackPythonType = Callable[[ArrayLike, int, int], ArrayLike]
142 Wrap a Python function of signature (x: ndarray[L,N], L, N) -> res
143 to a ctypes callback for C.
145 def c_callback(x_ptr, res_ptr, L, N):
151 x_raw = np.ctypeslib.as_array(x_ptr, shape=(size,))
152 x = x_raw.reshape((L, N))
155 res_val = func(x, L, N)
156 res_val = np.asarray(res_val, dtype=np.float64)
159 if res_val.ndim == 1:
161 if res_val.size != L:
162 raise ValueError(f
"Returned array has size {res_val.size}, expected {L}")
163 res_arr = np.ctypeslib.as_array(res_ptr, shape=(L,))
165 elif res_val.ndim == 2:
166 if res_val.shape != (L, N):
167 raise ValueError(f
"Returned array has shape {res_val.shape}, expected ({L},{N})")
169 res_row_major = res_val.flatten()
170 res_arr = np.ctypeslib.as_array(res_ptr, shape=(size,))
171 res_arr[:] = res_row_major
173 raise ValueError(f
"Returned array has invalid ndim {res_val.ndim}")
175 cb = ctypes_wrapper.wXCallbackCTypes(c_callback)