The goal of this example is to show how an existing C codebase for numerical computing (here c_code.c) can be wrapped in Cython to be exposed in Python.
The meat of the example is that the data is allocated in C, but exposed in Python without a copy using the PyArray_SimpleNewFromData numpy function in the Cython file cython_wrapper.pyx.
The purpose of the ArrayWrapper object, is to be garbage-collected by Python when the ndarray Python object disappear. The memory is then freed. Note that there is no control of when Python will deallocate the memory. If the memory is still being used by the C code, please refer to the following blog post by Travis Oliphant:
http://blog.enthought.com/python/numpy-arrays-with-pre-allocated-memory
You will need Cython, numpy, and a C compiler.
To build the C extension in-place run:
$ python setup.py build_ext -i
To test the C-Python bindings, run the test.py file.
Files | |
---|---|
c_code.c | The C code to bind. Knows nothing about Python |
cython_wrapper.c | The Cython code implementing the binding |
setup.py | The configure/make/install script |
test.py | Python code using the C extension |
Author: | Gael Varoquaux |
---|---|
License: | BSD 3 clause |
This is a terrific example; perfect starting point for a C/Python integration I have in mind. The code builds and runs cleanly on Fedora 14 and RHEL 4.x and 5.x machines I have access to. However a colleague with a 64 bit Windows 7 machine gets a build failure:
The error message:
C:\Users\steve\Desktop\gist1249305-8c4e86c6c0d86e796b27ee5a939fdd7b378d5058\gist1249305-8c4e86c6c0d86e796b27ee5a939
fdd7b378d5058> python setup.py build_ext --inplace
running build_ext
No module named msvccompiler in numpy.distutils; trying from distutils
cythoning .\cython_wrapper.pyx to .\cython_wrapper.c
building 'cython_wrapper' extension
creating build
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c
/nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27
\lib\site-packages\numpy\core\include -IC:\Python27\include
-IC:\Python27\PC /Tc.\cython_wrapper.c /Fobuild\temp.wi
n32-2.7\Release.\cython_wrapper.obj
Found executable C:\Program Files (x86)\Microsoft Visual Studio
9.0\VC\BIN\cl.exe
cython_wrapper.c
c:\users\steve\desktop\gist1249305-8c4e86c6c0d86e796b27ee5a939fdd7b378d5058\gist1249305-8c4e86c6c0d86e796b27ee5a939
fdd7b378d5058\c_code.c(13) : error C2143: syntax error : missing ';'
before 'type'
He can build and run other cython projects so the error above is a surprise (given the success on Linux). Do you have access to a Windows 7 box to test this code on? Or should we take this up on the cython mailing list?