0
votes

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?

1
TypeError aside, you shouldn't return a pointer to a ctypes array that's allocated in the callback. When string_allocator returns, the array's reference count decrements to 0, and it gets deallocated. You'll have to allocate the array in try_alloc, and then use whatever namespace resolution is most convenient for you to make it available to string_allocator (e.g. a global variable, a class, or closure). - Eryk Sun
The 'size' of the buffer is not known during the 'TryAlloc ' call. So I wanted to have an allocator within python and have the C doe invoke when populating the buffer. - user3279954
You are right, I edited the C routine to accept the buf alone. This is the expected signature, - user3279954
You still need to reference the allocated array object somewhere beyond the automatic lifetime of the callback scope, which leaves the problem of managing this reference. As I mentioned previously, you can use a global, class, or closure. The design will depend on the required lifetime and usage. e.g. does it need to support multiple allocations or concurrent allocations? Should it be a context manager, i.e. should an allocation's lifetime be determined by a with block? - Eryk Sun

1 Answers

0
votes

ctypes is trying to prevent you from crashing your program in a more serious manner. The object returned create_string_buffer owns the buffer it points to, and expects to free this buffer when the python object's reference count reaches 0. If you were to manually free this memory then the program would later result in a segmentation fault when the python object tried to free the buffer it points to. In fact you shouldn't try to free any memory that was allocated by the ctypes module. For instance:

i = c_int(10)
p = pointer(i)
vcrt_dll.free(p) # error

The only time you should manually free memory is for heap memory returned by a C library you are using (eg. vcrt_dll.malloc).