2

I have a Cython function like cdef generate_data(size) where I'd like to:

  • initialise an array of bytes of length size
  • call external (C) function to populate the array using array ptr and size
  • return the array as something understandable by Python (bytearray, bytes, your suggestions)

I have seen many approaches on the internet but I'm looking for the best/recommended way of doing this in my simple case. I want to:

  • avoid memory reallocations
  • avoid using numpy
  • ideally use something that works in Python 3 and 2.7, although a 2.7 solution is good enough.

I'm using Cython 0.20.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
zxxc
  • 355
  • 3
  • 12

1 Answers1

1

For allocating memory, I have you covered.

After that, just take a pointer (possibly at the data attribute if you use cpython.array.array like I recommend) and pass that along. You can return the cpython.array.array type and it will become a Python array.

Community
  • 1
  • 1
Veedrac
  • 58,273
  • 15
  • 112
  • 169