I am trying to pass different functions which have pointers as arguments to a python function. One example of the input function as input parameter is the given normal
function:
Sample.pyx
from cpython cimport array
import cython
import ctypes
cimport numpy as np
cpdef void normal(np.ndarray[ndim=1, dtype=np.float64_t] u,
np.ndarray[ndim=1, dtype=np.float64_t] yu,
np.ndarray[ndim=1, dtype=np.float64_t] ypu):
cdef int i
cdef int n=len(u)
for i in prange(n, nogil=True):
yu[i]=-u[i]*u[i]*0.5
ypu[i]=-u[i]
return
cdef class _SampleFunc:
cdef void (*func)(double *, double *, double *)
cdef void sample(int* x, double* hx, double* hxx, void(*func)(double*, double*, double*), int n):
def int i
for i from 0 <= i < n:
func[0](&x[i], &hx[i], &hxx[i])
return
cdef class myClass:
sample_wrapper = _SampleFunc()
sample_wrapper.func = Null
def foo(np.ndarray[ndim=1, dtype=np.float64_t] x,
np.ndarray[ndim=1, dtype=np.float64_t] hx,
np.ndarray[ndim=1, dtype=np.float64_t] hxx,
_SampleFunc sample_func,
int k):
cdef np.ndarray[ndim=1, dtype=np.float64_t] sp
cdef int num=len(x)
func = sample_func.func
assert func is not NULL, "function value is NULL"
cdef int j
for j from 0 <= j <k:
sample(&x[0],&hx[0], &hxx[0], func, num)
sp[j]=hx[0]
return sp
test.py
import numpy as np
from sample import *
x = np.zeros(10, float)
hx = np.zeros(10, float)
hpx = np.zeros(10, float)
x[0] = 0
x[1] = 1.0
x[2] = -1.0
def pynormal(x):
return -x*x*0.5,-x
hx[0], hpx[0] = pynormal(x[0])
hx[1], hpx[1] = pynormal(x[1])
hx[2], hpx[2] = pynormal(x[2])
num=20
ars=myClass()
s=ars.foo( x, hx, hpx, normal, num)
Running the test.py
code I am getting this error:
'ars._SampleFunc' object has no attribute 'func'
I am trying to write a wrapper for different C
functions which have three pointer arrays as their argument. My conclusion so far was that it can be done with a class, since the class can be accessible in python. I am wondering how I can pass the C
functions with pointer arrays as argument to myClass
class?
Update: Normal function
cdef void normal(
int n,
double* u,
double* yu,
double* ypu
):
cdef int i
for i in prange(n, nogil=True):
yu[i]=-u[i]*u[i]*0.5
ypu[i]=-u[i]
return