Commit fa44502b authored by gabrieldemarmiesse's avatar gabrieldemarmiesse

Reworked the tutorial for memoryviews.

parent 5f97a022
void multiply_by_10_in_C(double arr[], unsigned int n)
{
for (int i = 0; i < n; i++) {
arr[i] *= 10;
}
}
# distutils: sources=./C_func_file.c
# distutils: include_dirs=./
cdef extern from "C_func_file.h":
void multiply_by_10_in_C(double *, unsigned int)
import numpy as np
def multiply_by_10(arr): # 'arr' is a one-dimensional numpy array
if not arr.flags['C_CONTIGUOUS']:
arr = np.ascontiguousarray(arr) # Makes a contiguous copy of the numpy array.
cdef double[::1] arr_memview = arr
multiply_by_10_in_C(&arr_memview[0], arr_memview.shape[0])
return arr
a = np.ones(5, dtype=np.double)
print(multiply_by_10(a))
b = np.ones(10, dtype=np.double)
b = b[::2] # b is not contiguous.
print(multiply_by_10(b)) # but our function still works as expected.
.. _using_c_libraries:
****************** ******************
Using C libraries Using C libraries
****************** ******************
......
...@@ -296,42 +296,3 @@ There is some speed penalty to this though (as one makes more assumptions ...@@ -296,42 +296,3 @@ There is some speed penalty to this though (as one makes more assumptions
compile-time if the type is set to :obj:`np.ndarray`, specifically it is compile-time if the type is set to :obj:`np.ndarray`, specifically it is
assumed that the data is stored in pure strided mode and not in indirect assumed that the data is stored in pure strided mode and not in indirect
mode). mode).
Pass data from a C function via pointer
==================
Since use of pointers in C is ubiquitous, here we give a quick example of how
to call C functions whose arguments contain pointers. Suppose you want to
manage an array (allocate and deallocate) with NumPy, but its data are
computed by an external C function declared in :file:`C_func_file.h`::
void C_func(double * CPointer, unsigned int N);
where CPointer points to the array and N is its size.
You can call the function in a Cython file in the following way::
cdef extern from "C_func_file.h":
void C_func(double *, unsigned int)
import cython
import numpy as np
cimport numpy as np
def f(arr): # 'arr' is a one-dimensional array of size N
# Before calling the external function, we need to check whether the
# memory for 'arr' is contiguous or not; if not, we store the computed
# data in an contiguous array and then copy the data from that array.
np.ndarray[np.double_t, ndim=1, mode="c"] contig_arr
if arr.flags.c_contiguous:
contig_arr = arr
else:
contig_arr = arr.copy('C')
C_func(<cython.double *> contig_arr.data, contig_arr.size)
if contig_arr is not arr:
arr[...] = contig_arr
return
This way, you can have access the function more or less as a regular
Python function while its data and associated memory gracefully managed
by NumPy.
...@@ -691,6 +691,49 @@ reject None input straight away in the signature, which is supported in Cython ...@@ -691,6 +691,49 @@ reject None input straight away in the signature, which is supported in Cython
Unlike object attributes of extension classes, memoryview slices are not Unlike object attributes of extension classes, memoryview slices are not
initialized to None. initialized to None.
Pass data from a C function via pointer
=======================================
Since use of pointers in C is ubiquitous, here we give a quick example of how
to call C functions whose arguments contain pointers. Let's suppose you want to
manage an array (allocate and deallocate) with NumPy (it can also be Python arrays, or
anything that supports the buffer interface), but you want to perform computation on this
array with an external C function implemented in :file:`C_func_file.c`:
.. literalinclude:: ../../examples/memoryviews/C_func_file.c
:linenos:
This file have a header file called :file:`C_func_file.h` containing::
void multiply_by_10_in_C(double arr[], unsigned int n);
where ``arr`` points to the array and ``n`` is its size.
You can call the function in a Cython file in the following way:
.. literalinclude:: ../../examples/memoryviews/memview_to_c.pyx
:linenos:
Several things to note:
- ``&arr_memview[0]`` can be understood as 'the adress of the first element of the
memoryview'.
- ``arr_memview.shape[0]`` could have been replaced by ``arr_memview.size``,
``arr.shape[0]`` or ``arr.size``. But ``arr_memview.shape[0]`` is more efficient
because it doesn't require a conversion from a Python ``int`` to an
unsigned C integer.
- ``multiply_by_10`` will perform computation in-place if the array passed is contiguous,
and will return a new numpy array if ``arr`` is not contiguous.
- If you are using Python arrays instead of numpy arrays, you don't need to check
if the data is stored contiguously as this is always the case. See :ref:`array-array`.
This way, you can have access the function more or less as a regular
Python function while its data and associated memory gracefully managed
by NumPy. For the details of how to compile and
call functions in C files, see :ref:`using_c_libraries`.
.. _GIL: http://docs.python.org/dev/glossary.html#term-global-interpreter-lock .. _GIL: http://docs.python.org/dev/glossary.html#term-global-interpreter-lock
.. _new style buffers: http://docs.python.org/c-api/buffer.html .. _new style buffers: http://docs.python.org/c-api/buffer.html
.. _pep 3118: http://www.python.org/peps/pep-3118.html .. _pep 3118: http://www.python.org/peps/pep-3118.html
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment