I’m going in circles trying to figure out a fairly basic question in Cython. On the Python side, I have a list of variable-length strings. I need to pass these to a C++ function that will process this list and return some calculations (a vector of floats of same length as the input, if that matters). I know how to pass a single string, but I’m really struggling to figure out how to efficiently pass a list of multiple strings from Python->C++. I have no need to mutate the list of strings, the C++ side will treat them as read-only. The strings are coming from Python so they are a standard Python unicode string but they are guaranteed to be ASCII if that matters.
Could someone provide an example? I feel like this shouldn’t be too complicated but I can’t seem to find a good explanation. I’m definitely still getting the hang of Cython, so maybe I just don’t know the right terms to search for.
Advertisement
Answer
Lenormju’s first link had the solution. I didn’t know you could do memory views into a list, but the solution is much easier than I realized. A very simple minimal example:
# cython: language_level=3 # distutils: language = c++ from libcpp.vector cimport vector from libcpp.string cimport string cdef extern from "my_function_src.cc": cdef void my_function(vector[string] L) def call_my_function(L): cdef vector[string] L_buffer = L my_function(L_buffer)