Allocating memory to pass back via ctypes callback function

Scott scott.pigman at
Thu Jun 18 19:19:27 EDT 2009


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

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

    return 0



More information about the Python-list mailing list