Allocating memory to pass back via ctypes callback function

S

Scott

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
 
S

Scott

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 )

cstring.value = answer
p_cstring.contents = cstring
return
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top