python 如何键入提示ctypes.POINTER(ctypes.c_int)

fzsnzjdm  于 2023-05-16  发布在  Python
关注(0)|答案(1)|浏览(242)

下面是一个可以在mypy Playground上运行的MRE:

import ctypes
import numpy as np  # type: ignore # (no stubs for numpy)

def np_to_c(arr: np.ndarray) -> tuple[ctypes.POINTER(ctypes.c_int), ctypes.c_int]:
    return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), ctypes.c_int(len(arr))

这种类型的提示是错误的,根据mypy

main.py:4: error: Invalid type comment or annotation  [valid-type]
main.py:4: note: Suggestion: use ctypes.POINTER[...] instead of ctypes.POINTER(...)
Found 1 error in 1 file (checked 1 source file)

但是当我使用ctypes.POINTER[...]而不是ctypes.POINTER(...)时(参见下面的屏幕截图),我得到:

main.py:4: error: Function "ctypes.POINTER" is not valid as a type  [valid-type]
main.py:4: note: Perhaps you need "Callable[...]" or a callback protocol?
Found 1 error in 1 file (checked 1 source file)

amrnrhlw

amrnrhlw1#

ctypes.POINTER是一个构造函数,它为作为其参数传递的ctypes数据类型(c_int)创建一个对象(指针)。所以你的linter很可能会拒绝ctypes.POINTER(ctypes.c_int)作为类型提示,因为它实际上是一个函数调用。
ctypes.POINTER返回的所有对象都是从ctypes._Pointer派生的,所以我的选择是使用

def np_to_c(arr: np.ndarray) -> tuple[ctypes._Pointer, ctypes.c_int]:
    return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), ctypes.c_int(len(arr))

然而,这并没有真正表示返回的指针是专门针对c_int数组的。也会有兴趣听到一个更知情的意见对这件事!

相关问题