ctypes: delay conversion from c_char_p to string

Brendan Miller catphive at catphive.net
Thu Apr 22 23:34:11 CEST 2010


On Thu, Apr 22, 2010 at 7:49 AM, Zvezdan Petkovic <zvezdan at zope.com> wrote:
>
> On Apr 21, 2010, at 6:29 PM, Brendan Miller wrote:
>
>> Here's the method I was using. Note that tmp_char_ptr is of type
>> c_void_p. This should avoid the memory leak, assuming I am
>> interpreting the semantics of the cast correctly. Is there a cleaner
>> way to do this with ctypes?
>>
>>    def get_prop_string(self, prop_name):
>>        # Have to work with c_void_p to prevent ctypes from copying to a string
>>        # without giving me an opportunity to destroy the original string.
>>        tmp_char_ptr = _get_prop_string(self._props, prop_name)
>>        prop_val = cast(tmp_char_ptr, c_char_p).value
>>        _string_destroy(tmp_char_ptr)
>>        return prop_val
>
> Is this what you want?
>
> =====
>
> import ctypes.util
>
>
> libc = ctypes.CDLL(ctypes.util.find_library('libc'))
>
> libc.free.argtypes = [ctypes.c_void_p]
> libc.free.restype = None
> libc.strdup.argtype = [ctypes.c_char_p]
> libc.strdup.restype = ctypes.POINTER(ctypes.c_char)
>
>
> def strdup_and_free(s):
>    s_ptr = libc.strdup(s)
>    print s_ptr.contents
>    i = 0
>    while s_ptr[i] != '\0':
>        print s_ptr[i],
>        i += 1
>    print
>    libc.free(s_ptr)

Ah, so c_char_p's are converted to python strings by ctypes, but
POINTER(c_char) is *not*.

Thanks



More information about the Python-list mailing list