Skip to content
Advertisement

Example of passing a list of strings from Python to C++ function with Cython

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:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement