I have been looking at ways to allocate a buffer in Python and pass it safely to C, using the Python ctypes library.
As a first step I implemented a callback to allocate the buffer, with function type CFUNCTYPE(c_long, POINTER(c_void_p), c_long).
Version 1, using the CRT malloc:
def alloc(buf, size):
print type(buf)
print "allocating string of size-> ", size
buf[0] = vcrt_dll.malloc(size)
return 0
Version 2, using create_string_buffer:
def string_allocator(buf, size):
print type(buf)
print "allocating string of size-> ", size
buf[0] = create_string_buffer(size)
return 0
I am using the code below to pass the pointer to C. TryAlloc is some C function that populates a message for the Python caller.
C Code:
long TryAlloc(char **buf)
{
long size(256); // magic number !!!
allocator((void **)buf, size);
ZeroMemory(*buf, size);
char msg[] = "hello world";
strncpy_s(*buf, size, msg, strlen(msg));
return 0;
}
Python code:
def try_alloc():
buf = c_char_p()
sample_dll.TryAlloc(byref(buf))
print buf.value
When using malloc this works fine, but I need to manually invoke free for the allocated buffer. When I use the string buffer alternative, it raises the following error in Python:
TypeError: incompatible types, c_char_Array_100 instance instead of c_void_p
I saw some other threads discussing the same issue (For example, Calling python from C++, through callback, with variable buffer), but I couldn't find a proper solution for this. Can someone suggest a clean way of implementing this?
TypeErroraside, you shouldn't return a pointer to a ctypes array that's allocated in the callback. Whenstring_allocatorreturns, the array's reference count decrements to 0, and it gets deallocated. You'll have to allocate the array intry_alloc, and then use whatever namespace resolution is most convenient for you to make it available tostring_allocator(e.g. a global variable, a class, or closure). - Eryk Sunwithblock? - Eryk Sun