Allocating memory to pass back via ctypes callback function

Scott scott.pigman at gmail.com
Fri Jun 19 01:19:27 CEST 2009


Hi,

I'm using python ctypes to interact with the C API of a commercial-off-
the-shelf application.  I need to implement callback functions which
will be called by the application.  The callbacks take as a parameter
a char** parameter for which the callback function will allocate
memory and set the value of the underlying char*.  The hitch is that I
need to allocate the memory with the vendor's own memory allocation
function because the caller will free the memory with the
corresponding vendor free function.  The problem is that I can't quite
work out how to set the address of the incoming POINTER(c_char_p)
parameter to the location provided by the memory allocation function.

def my_callback(pointer_c_char_p):

    py_string = get_string_to_pass_back()

    address = VENDOR_malloc( len(py_string)*sizeof(c_char) )

    # ???? how to set pointer_c_char_p.contents to memory location
address?

    # ???? would this be the correct next thing to do?
    pointer_c_char_p.contents = c_char_p(py_string)
    # ????

    return 0

Thanks,

Scott



More information about the Python-list mailing list