[Cython] Memory views: dereferencing pointer does break strict-aliasing rules

Robert Bradshaw robertwb at gmail.com
Tue Jul 2 18:07:49 CEST 2013


On Tue, Jul 2, 2013 at 4:54 AM, Yury V. Zaytsev <yury at shurup.com> wrote:
> Hi,
>
> The simplest possible program using memory views compiles with a large
> number of warnings for me, even for a rather outdated version of gcc:
>
>     def hello(int [:] a):
>         print(a, "world")
>
> If I translate it with the latest released version of Cython like this:
>
>     cython cpp.pyx
>     cython --cplus cpp.pyx
>
> and compile like this:
>
>     gcc -O3 -march=native -Wall -fPIC -I/opt/ActivePython-2.7/include/python2.7 -c ./cpp.c -o cpp.o
>     g++ -O3 -march=native -Wall -fPIC -I/opt/ActivePython-2.7/include/python2.7 -c ./cpp.cpp -o cpp.o
>
> I get lots of warnings (see attached).
>
> It doesn't seem to be related to C++ as such, but rather it seems that
> the memory views code indeed somehow violates strict-aliasing rules.
>
> I'm not sure of how severe it is, but the documentation seems to suggest
> that this might even lead to incorrect results.
>
> Can this possibly be fixed in Cython and how important is that? Shall I
> create a bug report on the Trac? Is my only resort to test whether the
> compiler supports -fno-strict-aliasing and use that?

You should compile with -fno-strict-aliasing--if you were using
distutils rather than gcc directly it should add the all necessary
flags for you.

Aliasing different pointer types is necessary for Cython--it's how it
implements inheritance (in plain C, a PyObject* could be a pointer to
a list or dict or your own cdef class--pointer aliasing right there.
Also with memory views (and numpy arrays), the underlying data is
allocated as a char* and interpreted as a float* or int* or according
to the metadata in the array.

- Robert


More information about the cython-devel mailing list