Passing a list of strings to from python/ctypes to C function expecting char **

Viewed 12426

I have a C function which expects a list \0 terminated strings as input:

void external_C( int length , const char ** string_list) { 
   // Inspect the content of string_list - but not modify it.
} 

From python (with ctypes) I would like to call this function based on a list of python strings:

def call_c( string_list ):
    lib.external_C( ?? )

call_c( ["String1" , "String2" , "The last string"])

Any tips on how to build up the datastructure on the python side? Observe that I guarantee that the C function will NOT alter content of the strings in string_list.

Regards

joakim

4 Answers

Using ctypes

create list of expiries( strings)

expiries = ["1M", "2M", "3M", "6M","9M", "1Y", "2Y", "3Y","4Y", "5Y", "6Y", "7Y","8Y", "9Y", "10Y", "11Y","12Y", "15Y", "20Y", "25Y", "30Y"]

Logic to send string array

convert strings array to bytes array by looping in the array

 expiries_bytes = []
    for i in range(len(expiries)):
        expiries_bytes.append(bytes(expiries[i], 'utf-8'))

Logic ctypes to initiate a pointer with a length of array

expiries_array = (ctypes.c_char_p * (len(expiries_bytes)+1))()

assigning the byte array into the pointer

expiries_array[:-1] = expiries_bytes
Related