开发者

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 strings that python passes to C library are only read by the C library, so I am not worried about their memory management. AFAIK, their memory will be allocated by python and will be released when the python runtime seems it appropriate.

However, I understand that the memory of the string that C library returns has to be managed explicitly. One way I can implement it is: the C function callocs a character array, populates it with answer and returns from the function. The python code uses the r开发者_JS百科eturned string and should call libc's free on that string or call another function of the same C library which will take care of freeing the memory.

Is there any other way to do this? Does ctype offer any utility functions that simplify releasing the memory of data structures returned by native libraries?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜