如何使用python ctypes管理字符串内存 [英] How to manage string memory with python ctypes

查看:113
本文介绍了如何使用python ctypes管理字符串内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的python代码正在本机库(也由我编写)中调用C函数.该函数以两个字符串作为参数,并以字符串形式返回其响应. python传递给C库的两个参数字符串仅由C库读取,因此我不必担心它们的内存管理. AFAIK,它们的内存将由python分配,并在python运行时认为合适时释放.

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.

但是,我知道必须明确管理C库返回的字符串的内存.我可以实现它的一种方法是:C函数调用一个字符数组,在其中填充答案并从函数返回. python代码使用返回的字符串,并应在该字符串上调用libc的free或调用同一C库的另一个函数,该函数将释放内存.

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 returned 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.

还有其他方法可以做到吗? ctype是否提供任何实用程序功能来简化对本机库返回的数据结构的释放?

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?

推荐答案

我强烈建议不要在通过ctypes调用的外部函数中分配内存,并将此内存从Python中释放出来.尽可能在Python中分配内存.

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)

在Python中分配内存,并将指向该内存的指针传递给函数.

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

这篇关于如何使用python ctypes管理字符串内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆