【发布时间】:2012-11-30 12:03:29
【问题描述】:
如果我有一个可写的buffer,我可以使用ctypes.c_void_p.from_buffer 函数来获取指向这个缓冲区的C 指针。
但是,如何处理不可写缓冲区?如何形成一个const 指针,我可以将它传递给需要const void* 的C 代码,而无需制作不可写缓冲区的可写副本?
我考虑过c_void_p.from_address,但缓冲区(和内存视图)似乎没有公开它们的地址。
一些澄清:
>>> 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 的方法有效,但需要先复制缓冲区。我正在寻找解决缓冲区可写要求的方法,因为没有人会在那里写,我想避免数据的冗余复制。
【问题讨论】:
-
你能给出一些示例代码吗?
-
好了,我希望现在清楚了
-
所以这可能很有用 stackoverflow.com/questions/121396/… 。我尝试过尝试其中的建议,但收效甚微。诀窍很可能是编写一个 PythonC_API 函数来获取缓冲区并返回其地址。这应该相对容易做到。
标签: python python-2.7 buffer constants ctypes