Search code examples
cythonfwritetyped-memory-views

Can I `fwrite` a memory view in Cython?


Is it possible to write a numpy array to disk using a c fwrite function? From the Cython Memory View Documentation, I understand that "they can handle C arrays" but I do not see explicit examples of such.

Here's what I'm trying:

cdef FILE *fptr
fptr = fopen("data.dat", "w")
cdef double[:] array = numpy.array([.5, 1.5, 2.5, -9, 0.0, 5])
fwrite(array, sizeof(double), array.size, fptr)

But I get the following compile error:

Error compiling Cython file:
------------------------------------------------------------
...
def write_values(file_path):
    """Tracer code to write values to a C file."""
    cdef FILE *fptr
    fptr = fopen("data.dat", "w")
    cdef double[:] array = numpy.array([.5, 1.5, 2.5, -9, 0.0, 5])
    fwrite(array, sizeof(double), array.size, fptr)
          ^
------------------------------------------------------------

write_with_c.pyx:23:11: Cannot assign type 'double[:]' to 'const void *'

Is this possible to do?


Solution

  • Per the docs, you should be passing the address of the first element (double* should be convertable to const void* without casting), and for enforced correctness, you may want to explicitly declare the memoryview with cdef double[::1] array, which enforces a C-contiguous memory view, producing the final lines:

    cdef double[::1] array = numpy.array([.5, 1.5, 2.5, -9, 0.0, 5])
    fwrite(&array[0], sizeof(double), array.size, fptr)