分配sp时的附加括号

2024-04-19 06:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面一行代码。我或多或少知道它的功能—为缓冲区数组分配一些内存。我试图研究语法的含义-附加的括号是用来做什么的?第一个括号内的内容看起来不像函数。我看到如果一个函数嵌入到另一个函数中,就会使用双圆括号的结构,但看起来仍然不是这样。此外,如果不删除任何缓冲区变量(就好像它只是1)并不能生成1缓冲区数组,则必须删除该变量本身,否则在接下来的代码部分中,应用程序将崩溃。你知道吗

buffers = (ct.POINTER(ct.c_int8*buf_size)*no_ofBuffers)()

有人对这样的构造有更多的经验吗?你知道吗


Tags: 函数内存代码功能应用程序内容语法数组
1条回答
网友
1楼 · 发布于 2024-04-19 06:57:10

首先,这里是官方的ctypesdoc页面:[Python]: ctypes - A foreign function library for Python(您可能想看看数组部分)。

处理复杂表达式时始终适用的规则是:将其分解为更简单的表达式。我将从内部开始(指出所有中间步骤),并在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)

相关问题 更多 >