我在代码中包含以下行。我或多或少知道它的作用-为缓冲区数组分配一些内存。我正在尝试研究语法的含义-附加括号用于什么?第一个括号内的内容看起来不像一个函数。我看到如果将一个函数嵌入到另一个函数中,则使用双括号的构造,但是看起来却并非如此。此外,在删除no_ofBuffers变量(好像它只是1)时,如果不创建1-缓冲区数组,则变量本身是必需的,否则在代码的下一部分中,应用程序将崩溃。
buffers = (ct.POINTER(ct.c_int8*buf_size)*no_ofBuffers)()
有人对这样的构造有更多的经验吗?
答案 0 :(得分:0)
首先,这是官方的 ctypes 文档页面:[Python]: ctypes - A foreign function library for Python(您可能要看一下 Arrays 部分)。
处理复杂表达式时始终适用的规则是:将其分解为简单的表达式。我将从内部开始(指出所有中间步骤),并在 Python 控制台中进行操作(为了清楚起见,还更改了一些变量名):
>>> import sys >>> import ctypes >>> "Python {:s} on {:s}".format(sys.version, sys.platform) 'Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32' >>> >>> # Dummy values for numeric constants ... >>> INNER_ARR_SIZE = 8 # Replacement for buf_size >>> OUTER_ARR_SIZE = 10 # Replacement for no_ofBuffers >>> >>> # Declare all intermediary types ... >>> Int8Arr = ctypes.c_int8 * INNER_ARR_SIZE # Innermost "()" >>> Int8ArrPtr = ctypes.POINTER(Int8Arr) # Pointer >>> Int8ArrPtrArr = Int8ArrPtr * OUTER_ARR_SIZE # Outermost "()" >>> >>> # Use a human readable name for our final type ... >>> Buffers = Int8ArrPtrArr >>> >>> Buffers <class '__main__.LP_c_byte_Array_8_Array_10'> >>> type(Buffers) <class '_ctypes.PyCArrayType'> >>> >>> # At the end just instantiate the new type (that's what the "()" at the end do) to a default constructed value ... >>> buffers = Buffers() # THIS is the equivalent of your (complex) expression >>> buffers <__main__.LP_c_byte_Array_8_Array_10 object at 0x00000235F614A9C8> >>> type(buffers) <class '__main__.LP_c_byte_Array_8_Array_10'> >>> len(buffers) 10 >>> >>> # It's similar to what the line below does ... >>> i = ctypes.c_int() >>> i c_long(0)