python - ctypes 中的 const void* 指针

标签 python python-2.7 buffer constants ctypes

如果我有一个可写的 buffer,我可以使用 ctypes.c_void_p.from_buffer 函数来获取指向该缓冲区的 C 指针。

但是如何处理不可写的缓冲区呢?如何形成一个 const 指针,我可以将其传递给需要 const void* 的 C 代码,而无需求助于制作不可写缓冲区的可写副本?

我考虑过 c_void_p.from_address 但缓冲区(和内存 View )似乎没有公开它们的地址。


一些说明:

>>> import ctypes
>>> b = buffer("some data that supports the buffer interface, like a str")
>>> ptr = ctypes.c_void_p.from_buffer(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: buffer is read-only
>>> ptr = ctypes.c_void_p.from_buffer_copy(b)    # works, but has to copy data
>>> ptr = ctypes.CONST(c_void_p).from_buffer(b)  # (I'm making this one up)
>>> ptr = ctypes.c_void_p.from_address(???)      # could work; how to get addr?

这将与 void some_api(const void* read_only_data) 一起工作,例如:

>>> ctypes.cdll.LoadLibrary(some_lib).some_api(ptr)

from_buffer_copy 的方法有效,但需要先复制缓冲区。我正在寻找解决缓冲区可写要求的方法,因为没有人会在那里写,我想避免数据的冗余复制。

最佳答案

您可以使用 ctypes 将 Python 字符串转换为 char*,它指向存储 Python 字符串数据的实际内存。

随意双投。

关于python - ctypes 中的 const void* 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13845608/

相关文章:

python - 如何使用 python 或 shell 比较两个文件时获取完整行

python - 如何设置当前工作目录?

python - 按下按钮时的wxpython刷新窗口

php - 同时停止并返回输出缓冲

windows - 告诉 Emacs 在特定窗口中打开新缓冲区

c++ - 如何在内存缓冲区上实现 seekg/seekpos?

python - Tensorflow:噪声对比估计语言模型

python - XPath:通过当前节点属性选择当前和下一个节点的文本

python-2.7 - 检查 Pyspark Dataframe 中的重复项

Python raw_input 使用 TAB 而不是 ENTER?