Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass a Numpy array into a cffi function and how to get one back out?
    primarykey
    data
    text
    <p>I am developing an audio algorithm using Python and Numpy. Now I want to speed up that algorithm by implementing a part of it in C. In the past, <a href="http://bastibe.de/real-time-signal-processing-in-python.html">I have done this using cython</a>. Now I want to do the same thing using the new <a href="https://cffi.readthedocs.org/en/release-0.6/">cffi</a>.</p> <p>For testing purposes, I wrote a trivial C function:</p> <pre><code>void copy(float *in, float *out, int len) { for (int i=0; i&lt;len; i++) { out[i] = in[i]; } } </code></pre> <p>Now I want to create two numpy arrays and have those be processed by this function. I figured out a way to do that:</p> <pre><code>import numpy as np from cffi import FFI ffi = FFI() ffi.cdef("void copy(float *in, float *out, int len);") C = ffi.dlopen("/path/to/copy.dll") float_in = ffi.new("float[16]") float_out = ffi.new("float[16]") arr_in = 42*np.ones(16, dtype=np.float32) float_in[0:16] = arr_in[0:16] C.copy(float_in, float_out, 16) arr_out = np.frombuffer(ffi.buffer(float_out, 16*4), dtype=np.float32) </code></pre> <p>However, I would like to improve this code: </p> <ol> <li>Is there a way to directly access the underlying float buffers of the numpy arrays without copying them?</li> <li><code>ffi.buffer</code> is very convenient for quickly converting to contents of a C array to a Numpy array. Is there an equivalent way for quickly converting a numpy array into a C array without copying the individual elements?</li> <li>For some applications, <code>float_in[0:16] = arr_in[0:16]</code> is a convenient way of accessing data. The opposite, <code>arr_out[0:16] = float_out[0:16]</code> does not work however. Why not?</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload