如何创建 Python 不会释放的缓冲区?

发布于 2024-11-17 18:23:24 字数 405 浏览 3 评论 0原文

我需要从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

压抑⊿情绪 2024-11-24 18:23:24

按给定顺序尝试以下操作:

  1. 尝试使用 Python 来管理内存,例如使用 create_string_buffer()。如果您可以控制 C 函数的行为,请将其修改为不 free() 缓冲区。

  2. 如果您调用的库函数在使用缓冲区后释放缓冲区,则必须有某个库函数分配缓冲区(或者库已损坏)。

  3. 当然,您可以通过ctypes调用malloc(),但这会破坏内存管理的所有良好实践。将其用作最后的手段。几乎可以肯定,这会在以后引入难以发现的错误。

Try the following in the given order:

  1. 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 not free() the buffer.

  2. 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).

  3. Of course you could call malloc() via ctypes, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文