From: Brendan Miller on
I have a function exposed through ctypes that returns a c_char_p.
Since I need to deallocate that c_char_p, it's inconvenient that
ctypes copies the c_char_p into a string instead of giving me the raw
pointer. I believe this will cause a memory leak, unless ctypes is
smart enough to free the string itself after the copy... which I
doubt.

Is there some way to tell ctypes to return an actual c_char_p, or is
my best bet to return a c_void_p and cast to c_char_p when I'm reading
to convert to a string?

Thanks
Brendan
From: Brendan Miller on
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

On Wed, Apr 21, 2010 at 3:15 PM, Brendan Miller <catphive(a)catphive.net> wrote:
> I have a function exposed through ctypes that returns a c_char_p.
> Since I need to deallocate that c_char_p, it's inconvenient that
> ctypes copies the c_char_p into a string instead of giving me the raw
> pointer. I believe this will cause a memory leak, unless ctypes is
> smart enough to free the string itself after the copy... which I
> doubt.
>
> Is there some way to tell ctypes to return an actual c_char_p, or is
> my best bet to return a c_void_p and cast to c_char_p when I'm reading
> to convert to a string?
>
> Thanks
> Brendan
>
From: Thomas Heller on
Brendan Miller schrieb:
> I have a function exposed through ctypes that returns a c_char_p.
> Since I need to deallocate that c_char_p, it's inconvenient that
> ctypes copies the c_char_p into a string instead of giving me the raw
> pointer. I believe this will cause a memory leak, unless ctypes is
> smart enough to free the string itself after the copy... which I
> doubt.
>
> Is there some way to tell ctypes to return an actual c_char_p, or is
> my best bet to return a c_void_p and cast to c_char_p when I'm reading
> to convert to a string?

Yes, there is. When you create a subclass of c_char_p (or any other 'simple'
ctypes type like c_wchar_p or even c_int and alike) then the automatic conversion
to native Python types like string, unicode, integer is not done.
The function will return an instance of that specific class; you can
retrive the value via the .value property and deallocate the resources
in the destructor for example.


--
Thanks,
Thomas