2
我有一個模板化的C++函數,我希望能夠使用這兩種類型。由於Python不支持重載,我有點卡住如何解決這個問題。我有一個.pyx
如下所示。我如何在float
和double
中使用C++函數?如何在C++中爲Cython中的兩種類型使用模板化函數?
import cython
import numpy as np
cimport numpy as np
# declare the interface to the C code
cdef extern from "diff_cpp.cpp" namespace "diff":
cdef void diff_cpp[float] (float* at, const float* a, const float visc,
const float dxidxi, const float dyidyi, const float dzidzi,
const int itot, const int jtot, const int ktot)
cdef extern from "diff_cpp.cpp" namespace "diff":
cdef void diff_cpp[double] (double* at, const double* a, const double visc,
const double dxidxi, const double dyidyi, const double dzidzi,
const int itot, const int jtot, const int ktot)
@cython.boundscheck(False)
@cython.wraparound(False)
def diff(np.ndarray[double, ndim=3, mode="c"] at not None,
np.ndarray[double, ndim=3, mode="c"] a not None,
double visc, double dxidxi, double dyidyi, double dzidzi):
cdef int ktot, jtot, itot
ktot, jtot, itot = at.shape[0], at.shape[1], at.shape[2]
diff_cpp[double](&at[0,0,0], &a[0,0,0], visc, dxidxi, dyidyi, dzidzi, itot, jtot, ktot)
return None
@cython.boundscheck(False)
@cython.wraparound(False)
def diff_f(np.ndarray[float, ndim=3, mode="c"] at not None,
np.ndarray[float, ndim=3, mode="c"] a not None,
float visc, float dxidxi, float dyidyi, float dzidzi):
cdef int ktot, jtot, itot
ktot, jtot, itot = at.shape[0], at.shape[1], at.shape[2]
diff_cpp[float](&at[0,0,0], &a[0,0,0], visc, dxidxi, dyidyi, dzidzi, itot, jtot, ktot)
return None
用解決
UPDATE @ OZ1的答案提供了這樣做的正確方法。這個代碼適用於那些對解決這個特定問題感興趣的人。
import cython
import numpy as np
cimport numpy as np
# declare the interface to the C code
cdef extern from "diff_cpp.cpp" namespace "diff":
cdef void diff_cpp[T](T* at, const T* a, const T visc,
const T dxidxi, const T dyidyi, const T dzidzi,
const int itot, const int jtot, const int ktot)
ctypedef fused float_t:
cython.float
cython.double
@cython.boundscheck(False)
@cython.wraparound(False)
def diff(np.ndarray[float_t, ndim=3, mode="c"] at not None,
np.ndarray[float_t, ndim=3, mode="c"] a not None,
float_t visc, float_t dxidxi, float_t dyidyi, float_t dzidzi):
cdef int ktot, jtot, itot
ktot, jtot, itot = at.shape[0], at.shape[1], at.shape[2]
diff_cpp(&at[0,0,0], &a[0,0,0], visc, dxidxi, dyidyi, dzidzi, itot, jtot, ktot)
return None
只是spitballing,你試圖做一個typedef的特定模板實例,並給予非模板名稱到Python? –