Ways to include C #define'd constants in Cython .PXD file

2,670 views
Skip to first unread message

Vogon

unread,
Dec 17, 2009, 7:16:49 AM12/17/09
to cython-users
Hi,

I'm wondering what different ways there are to directly include C
compile-time constants in a PXD file. So far I've found that the
following works:

// foo.h
#define C_BAR 1

# foo.pxd
cdef extern from 'foo.h':
int C_BAR


However, I'm worried that the PXD version of the constant is allocated
on the "stack" instead of the "heap" and having an enormous amount of
such definitions would cause a performance hit. Is this what happens
in reality? If so, are there any more efficient/convenient ways to do
the same thing?

Robert Bradshaw

unread,
Dec 17, 2009, 8:03:00 AM12/17/09
to cython...@googlegroups.com

The extern block only tells Cython what it can count on finding in the
referenced header file. In this case the literal "C_BAR" will get
written write out to the .c file wherever it is used, and the C
compiler will do the right thing (in this case, probably inserting a
compile time constant).

- Robert

Vogon

unread,
Dec 17, 2009, 8:43:30 AM12/17/09
to cython-users
Good to know. Thanks!

On Dec 17, 3:03 pm, Robert Bradshaw <rober...@math.washington.edu>
wrote:

Lisandro Dalcín

unread,
Dec 17, 2009, 10:05:45 AM12/17/09
to cython...@googlegroups.com
On Thu, Dec 17, 2009 at 9:16 AM, Vogon <jus...@gmail.com> wrote:
> Hi,
>
> I'm wondering what different ways there are to directly include C
> compile-time constants in a PXD file. So far I've found that the
> following works:
>
> // foo.h
> #define C_BAR 1
>
> # foo.pxd
> cdef extern from 'foo.h':
>    int C_BAR
>

For integrals, I think it is better to do it like this:

cdef extern from 'foo.h':
   enum: C_BAR

That way, Cython is going to treat C_BAR as a constant, you can do for example:

cdef double my_array[C_BAR]


--
Lisandro Dalcín
---------------
Centro Internacional de Métodos Computacionales en Ingeniería (CIMEC)
Instituto de Desarrollo Tecnológico para la Industria Química (INTEC)
Consejo Nacional de Investigaciones Científicas y Técnicas (CONICET)
PTLC - Güemes 3450, (3000) Santa Fe, Argentina
Tel/Fax: +54-(0)342-451.1594

Reply all
Reply to author
Forward
0 new messages