如果我有一个可写的缓冲区(buffer),我可以使用ctypes.c_void_p.from_buffer函数获取指向该缓冲区的C指针。
但是如何处理不可写的缓冲区呢?如何形成一个const指针,以便将其传递给期望const void*的C代码,而不必通过制作不可写缓冲区的可写副本来实现?
我考虑了c_void_p.from_address,但缓冲区(和内存视图)似乎没有暴露它们的地址。
一些澄清:
但是如何处理不可写的缓冲区呢?如何形成一个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
方法可以使用,但需要先复制缓冲区。我正在寻找一种方法来避免需要可写的缓冲区的要求,因为没有人会在那里写入,而且我想避免数据的冗余复制。
void*
,可以直接将str
/unicode
(Python 2.x)或bytes
/str
(Python 3.x)传递给函数。 - Mark Tolonen