问题
I try to conditionally compile (or generate) to c code from a Cython pxd. I read that I can DEF to define aa value and IF to conditionally generate based on its value, but how can I get this value to get from outside of the pxd file?
Specifically these two cases are interesting for me now:
- give some command-line define to Cython, preferrably through the Cython.Distutils setuptools way
- the extern-ed C header file defines some value, and conditionally define using Cython based on this value (maybe impossible now?)
Thank you
回答1:
You could generate a pxi file, and include it before doing your IF (same as ./configure generate a config.h too.) This is what we do in Kivy setup.py for example :
c_options = {
'use_opengl_es2': True,
'use_opengl_debug': False,
'use_glew': False,
'use_mesagl': False}
print 'Generate config.pxi'
with open(join(dirname(__file__), 'kivy', 'graphics', 'config.pxi'), 'w') as fd:
for k, v in c_options.iteritems():
fd.write('DEF %s = %d\n' % (k.upper(), int(v)))
And then, in your pxd :
include "config.pxi"
IF USE_OPENGL_DEBUG == 1:
# do other import or whatever you want
回答2:
Actually, the second option is easier. Create a FLAG in some .h file and then do
cdef extern from "header.h":
cdef int FLAG
then when you want to use it, just write
if FLAG:
...
and even though Cython will generate the code, the C compiler will automatically trim this away as it knows the value of FLAG at compile time.
来源:https://stackoverflow.com/questions/3826458/cython-conditional-compile-based-on-external-value