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

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)


Solution 1:[1]

According to [Python.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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1