Ctypes: best way to read C string from shared library

I had the impression that c_char_p would recognize the null character that terminates a C string.
I’m curious to ask the recommended (idiomatic) way to get a Python string from a symbol in the read-only data section of a shared library.

Python 3.13.5 (main, May  5 2026, 21:05:52) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> lib = ctypes.CDLL(None)
>>> ptr = ctypes.c_char_p.in_dll(lib, '_libc_intl_domainname')
>>> name = str(ptr, 'ascii')
>>> name
'libc\x00 gl'
>>> name[0:name.find('\x00')]
'libc'
>>> ptr.value
Segmentation fault

It’s not the null terminator that’s the problem, it’s that you’re treating it as a pointer to a string when what you really have is just the string itself.

You could try:

ptr = ctypes.cast(lib.whatever_the_name_of_the_thing_is, ctypes.c_char_p)
name = ptr.value

Yes, thank you, that works:

>>> import ctypes
>>> lib = ctypes.CDLL(None)
>>> ptr = ctypes.cast(lib._libc_intl_domainname, ctypes.c_char_p)
>>> ptr.value
b'libc'

And this works too:

>>> import ctypes
>>> lib = ctypes.CDLL(None)
>>> ctypes.string_at(lib._libc_intl_domainname)
b'libc'