如何创建 Python 不会释放的缓冲区?
我需要从 python 调用 C 库中的函数,这将 free() 参数。 所以我尝试了create_string_buffer(),但似乎这个缓冲区稍后会被Python释放,这将使缓冲区被释放两次。
我在网上读到Python会对缓冲区进行重新计数,并在没有引用时释放它们。那么我怎样才能创建一个Python以后不会关心的缓冲区呢?谢谢。
例子: 我使用以下命令加载 dll:lib = cdll.LoadLibrary("libxxx.so")
,然后使用以下命令调用该函数:path = create_string_buffer(topdir)
和 lib .load(路径)
。但是,libxxx.so 中的加载函数将释放其参数。后来“path”会被Python释放,所以它被释放了两次
I need to call a function in a C library from python, which would free() the parameter.
So I tried create_string_buffer(), but it seems like that this buffer would be freed by Python later, and this would make the buffer be freed twice.
I read on the web that Python would refcount the buffers, and free them when there is no reference. So how can I create a buffer which python would not care about it afterwards? Thanks.
example:
I load the dll with: lib = cdll.LoadLibrary("libxxx.so")
and then call the function with: path = create_string_buffer(topdir)
and lib.load(path)
. However, the load function in the libxxx.so would free its argument. And later "path" would be freed by Python, so it is freed twice
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按给定顺序尝试以下操作:
尝试使用 Python 来管理内存,例如使用
create_string_buffer()
。如果您可以控制 C 函数的行为,请将其修改为不free()
缓冲区。如果您调用的库函数在使用缓冲区后释放缓冲区,则必须有某个库函数分配缓冲区(或者库已损坏)。
当然,您可以通过
ctypes
调用malloc()
,但这会破坏内存管理的所有良好实践。将其用作最后的手段。几乎可以肯定,这会在以后引入难以发现的错误。Try the following in the given order:
Try by all means to manage your memory in Python, for example using
create_string_buffer()
. If you can control the behaviour of the C function, modify it to notfree()
the buffer.If the library function you call frees the buffer after using it, there must be some library function that allocates the buffer (or the library is broken).
Of course you could call
malloc()
viactypes
, but this would break all good practices on memory management. Use it as a last resort. Almost certainly, this will introduce hard to find bugs at some later time.