How to annotate pointer to C character array in method signature?

别来无恙 提交于 2019-12-24 10:47:48

问题


I am writing a wrapper for a C library in Python. I am trying to properly annotate all of the methods, so my IDE can help me catch errors. I am stuck annotating one method, can you help me figure out the proper annotation?

One of the methods in the C library works as follows:

  1. Takes one arg: pointer to a character buffer

    • Buffer is made via: char_buffer = ctypes.create_string_buffer(16)
  2. Populates the char buffer with the output value

    • Done via CMethod(char_buffer)

One then parses the buffer by doing something like char_buffer.value.

How can I annotate the wrapper method to look for a pointer to a character buffer? Currently, I have the below, but I think this is incorrect, since POINTER seems to be just a function in _ctypes.py.

from ctypes import POINTER

def wrapped_method(char_buffer: POINTER):
    CMethod(char_buffer)

回答1:


According to [Python 3.Docs]: ctypes.create_string_buffer(init_or_size, size=None):

This function creates a mutable character buffer. The returned object is a ctypes array of c_char.

Example:

>>> import ctypes
>>>
>>> CharArr16 = ctypes.c_char * 16
>>> s = ctypes.create_string_buffer(16)
>>>
>>> isinstance(s, CharArr16)
True
>>> isinstance(s, ctypes.c_char * 15)
False
>>> isinstance(s, ctypes.c_char * 17)
False
>>>
>>> # A more general form, but it WILL FAIL for non array instances
...
>>> isinstance(s, s._type_ * s._length_)
True
>>>
>>> # A more general form that WILL WORK
...
>>> issubclass(CharArr16, ctypes.Array)
True
>>> isinstance(s, ctypes.Array)
True


来源:https://stackoverflow.com/questions/57084381/how-to-annotate-pointer-to-c-character-array-in-method-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!