Allocating memory to pass back via ctypes callback function

Nick Craig-Wood nick at craig-wood.com
Mon Jun 22 11:29:28 CEST 2009


Scott <scott.pigman at gmail.com> wrote:
>  I think I found the answer to my own question.  Can anyone spot any
>  issues with the following solution? The application I'm writing will
>  be hitting these callbacks pretty heavily so I'm nervous about mucking
>  up the memory management and creating one of those bugs that passes
>  undetected through testing but nails you in production.
> 
>  def my_callback(p_cstring):
>      answer = 'foobar'
> 
>      address = VENDOR_malloc(len(answer)+1)
> 
>      cstring = c_char_p.from_address( address )

I think this allocates the pointer (the c_char_p) in the malloced
block, not the actual data...

>      cstring.value = answer

And this overwrites the pointer

>      p_cstring.contents = cstring
>      return

If you try this, it gives all sorts of rubbish data / segfaults

memmove(address, address+1, 1)

Here is how I'd do it

from ctypes import *
from ctypes.util import find_library

c_lib = CDLL(find_library("c"))
malloc = c_lib.malloc
malloc.argtypes = [c_long]
malloc.restype = c_void_p

answer = 'foobar\0'

address = malloc(len(answer))
print address

cstring = c_char_p()
print addressof(cstring)

cstring.value = address
memmove(address, answer, len(answer))
print cstring.value
memmove(address, address+1, 1)
print cstring.value

Which prints

159611736
3084544552
foobar
ooobar


-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list