Search code examples
pythonctypes

python ctypes: reading a string array


With python ctypes, how can I read a NUL-terminated array of NUL-terminated strings, e.g. ghostscript's gs_error_names ?

I know how to get the first value:

from ctypes import *
from ctypes.util import find_library

gs = CDLL(find_library("gs"))
print(c_char_p.in_dll(gs, 'gs_error_names').value)

I also know how to get a fixed number of values:

print(list((c_char_p * 10).in_dll(gs, 'gs_error_names')))

But how can I read all values until the end of the array?


Solution

  • from ctypes import *
    from ctypes.util import find_library
    
    gs = CDLL(find_library("gs"))
    error_names_ptr = cast(gs.gs_error_names, POINTER(c_char_p))
    error_names = []
    i = 0
    while val := error_names_ptr[i]:
        error_names.append(val)
        i += 1
    print(error_names)
    

    The key was to access the attribute directly and cast(), rather than using in_dll(), which segfaults.