Python元组到Cython Struct

时间:2014-02-27 20:10:57

标签: python scipy tuples cython

Scipy splprep(spline preperation)产生一个Tuple tckp

tckp:tuple(t,c,k)一个包含结矢量的元组,                      B样条系数和样条的程度。

tckp = [array[double,double ,..,double], 
       [array[double,double ,..,double],          
        array[double,double ,..... ,double], 
        array[double,double ,..... ,double]], int]                                        

如何构建和填充等效的Cython结构才能使用

Cython中的splev(样条评估)

1 个答案:

答案 0 :(得分:0)

正如评论中所讨论的,这取决于您将tckp传递给其他函数的方式。存储此信息并传递给其他函数的一种方法是使用struct

在下面的示例中,您使用tckpstruct列表传递给cdef函数,该函数以void *为输入,模拟C函数...示例函数为所有数组添加1,假设int0是数组的大小。

import numpy as np
cimport numpy as np

cdef struct type_tckp_struct:
    double *array0
    double *array1
    double *array2
    double *array3
    int *int0

def main():
    cdef type_tckp_struct tckp_struct
    cdef np.ndarray[np.float64_t, ndim=1] barray0, barray1, barray2, barray3
    cdef int bint

    tckp = [np.arange(1,11).astype(np.float64),
            2*np.arange(1,11).astype(np.float64),
            3*np.arange(1,11).astype(np.float64),
            4*np.arange(1,11).astype(np.float64), 10]
    barray0 = tckp[0]
    barray1 = tckp[1]
    barray2 = tckp[2]
    barray3 = tckp[3]
    bint = tckp[4]
    tckp_struct.array0 = &barray0[0]
    tckp_struct.array1 = &barray1[0]
    tckp_struct.array2 = &barray2[0]
    tckp_struct.array3 = &barray3[0]
    tckp_struct.int0 = &bint

    intern_func(&tckp_struct)

cdef void intern_func(void *args):
    cdef type_tckp_struct *args_in=<type_tckp_struct *>args
    cdef double *array0
    cdef double *array1
    cdef double *array2
    cdef double *array3
    cdef int int0, i
    array0 = args_in.array0
    array1 = args_in.array1
    array2 = args_in.array2
    array3 = args_in.array3
    int0 = args_in.int0[0]

    for i in range(int0):
        array0[i] += 1
        array1[i] += 1
        array2[i] += 1
        array3[i] += 1