Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional `ctypedef` with Cython

Tags:

python

c

cython

I need access to the uint64_t typedef from stdint.h in some wrapper code that I'm writing and I can't figure out how to get it done. The problem is that from what I can tell from the docs, my ctypedef will have to take the form:

ctypedef unsigned long uint64_t

or

ctypedef unsigned long long uint64_t

depending on if WORDSIZE from bits/wordsize.h is 64 or 32. I haven't been able to find out out how to get access to this preprocessor definition from Cython and if I could, Cython doesn't seem to like ctypedef statements in if statements and when I try to put an if statement in a cdef block, it seems to confuse it with a declaration. Any ideas? Hopefully I'm just missing something really basic here.

like image 686
aaronasterling Avatar asked Aug 23 '10 01:08

aaronasterling


People also ask

How do you define a function in Cython?

There are two kinds of function definition in Cython: Python functions are defined using the def statement, as in Python. They take Python objects as parameters and return Python objects. C functions are defined using the cdef statement in Cython syntax or with the @cfunc decorator.

What is Cdef extern?

The cdef extern from clause does three things: It directs Cython to place a #include statement for the named header file in the generated C code. It prevents Cython from generating any C code for the declarations found in the associated block.


1 Answers

cdef extern from "stdint.h":
    ctypedef unsigned long long uint64_t

Any ctypedef that's extern'd won't have a typedef generated in the .c file. Cython will include stdint.h and your C compiler will use the actual typedef from there.

The only thing that the type provided matters for is when cython generates code that automatically converts between C types and Python types. Using unsigned long long means that Cython will use PyLong_FromUnsignedLongLong and PyLong_AsLongLongAndOverflow. This way, you hopefully won't get any truncation on conversion.

like image 134
habnabit Avatar answered Sep 29 '22 10:09

habnabit