3

Specifically:

  • How to provide numpy.ndarray as a function output data type and
  • How to use cimport numpy instead of import numpy to create an array without Python overhead?

The code below works if numpy.ndarray is removed from the line cdef numpy.ndarray array(int start, int end):. According to the annotation it still has a lot of Python overhead (excluding the range(start, end) initialisation of the C++ vector).

%%cython -a
# distutils: language = c++

import numpy
from libcpp.vector cimport vector


cdef numpy.ndarray array(int start, int end):
    cdef vector[int] vect = range(start, end)
    return numpy.array(vect)

print(array(1,15))
Greg
  • 8,175
  • 16
  • 72
  • 125
  • 1
    [This isn't quite a duplicate](https://stackoverflow.com/questions/45133276/passing-c-vector-to-numpy-through-cython-without-copying-and-taking-care-of-me) but it is pretty relevant. – DavidW Aug 29 '18 at 18:53

1 Answers1

1

NumPy arrays are Python object. If you wish to work with them at the compiled level you should use memoryviews that are supported by Cython. You can then require a np.asarray(cython_memoryview_variable) to go to Python.

As your base object is a C++ vector, there is no automatic conversion of its content to a NumPy arrray, so you have to work that out explicitly (at the cost of a copy).

Pierre de Buyl
  • 7,074
  • 2
  • 16
  • 22