问题描述
我在 cpython 3.6 中使用 Cython,我想将一些指针标记为“非别名”,以提高性能并在语义上明确。
在 C 中,这是通过 restrict
(__restrict
,__restrict__
) 关键字完成的。但是如何在 Cython restrict
代码中对我的 cdef
变量使用 .pyx
?
谢谢!
解决方法
Cython 没有对 restrict
关键字的语法/支持(还没有?)。最好的办法是用 C 编写这个函数,最方便的可能是使用 verbatim-C-code,例如这里有一个虚拟示例:
%%cython
cdef extern from *:
"""
void c_fun(int * CYTHON_RESTRICT a,int * CYTHON_RESTRICT b){
a[0] = b[0];
}
"""
void c_fun(int *a,int *b)
# example usage
def doit(k):
cdef int i=k;
cdef int j=k+1;
c_fun(&i,&j)
print(i)
这里我使用 Cython 的(未记录的)定义 CYTHON_RESTRICT
,其中 is defined 为
// restrict
#ifndef CYTHON_RESTRICT
#if defined(__GNUC__)
#define CYTHON_RESTRICT __restrict__
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define CYTHON_RESTRICT __restrict
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_RESTRICT restrict
#else
#define CYTHON_RESTRICT
#endif
#endif
所以它不仅适用于符合 C99 的 c 编译器。然而,从长远来看,最好定义一些类似的东西,而不是依赖于未记录的功能。