How to use the `restrict` keyword in Cython?
Asked Answered
H

1

6

I'm using Cython in CPython 3.6 and I'd like to mark some pointers as "not aliased", to improve performance and be explicit semantically.

In C this is done with the restrict (__restrict, __restrict__) keyword. But how do I use restrict on my cdef variables from a Cython .pyx code?

Thanks!

Hackberry answered 18/5, 2021 at 23:58 Comment(0)
F
7

Cython doesn't have syntax/support for the restrict-keyword (yet?). Your best bet is to code this function in C, most convenient is probably to use verbatim-C-code, e.g. here for a dummy example:

%%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)

Here I use Cython's (undocumented) define CYTHON_RESTRICT, which is defined as

// 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

so it works not only for C99-compliant c-compiler. In the long run however, it is probably best to define something similar and not to depend on undocumented features.

Fardel answered 19/5, 2021 at 6:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.