Skip to content Skip to sidebar Skip to footer

How To Manage String Memory With Python Ctypes

My python code is calling a C function in a native library (also written by me). The function takes two strings as arguments and returns its response as a string. The two argument

Solution 1:

I'd recommend strongly against memory allocation in a foreign function called via ctypes and freeing this memory from Python. Whenever possible, allocate the memory in Python.

In your case, if you know in advance an upper limit for the length of the returned string, use

buf = ctypes.create_string_buffer(upper_limt)

to allocate the memory in Python and pass a pointer to this memory to your function.

Solution 2:

A common way to do this is adding an additional buffer parameter and a length parameter to the C function. If the function is called with a buffer size that is smaller than the required size, the function simply returns the required buffer size and performs no other action, otherwise, the data is copied into the buffer and the size is set to the actual size of the data copied.

This allows you to manage the buffer in Python, at the expense of adding 2 additional parameters to your C function.

Post a Comment for "How To Manage String Memory With Python Ctypes"