Skip to content

gh-69011: ctypes.create_*_buffer clarify NUL termination character inclusion #132858

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

StanFromIreland
Copy link
Contributor

@StanFromIreland StanFromIreland commented Apr 23, 2025

There was little support for raising errors so a docs note is probably the best thing to do -- atleast for now


📚 Documentation preview 📚: https://cpython-previews--132858.org.readthedocs.build/

Copy link
Member

@ZeroIntensity ZeroIntensity left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks fine. I'll tag @encukou as the current ctypes expert, but be aware he's currently on leave.

@encukou
Copy link
Member

encukou commented Apr 28, 2025

I'd write it like this, to also mention what happens if size is too large:

.. function:: create_string_buffer(init, size=None)
              create_string_buffer(size)

   Create a mutable character buffer. The returned object is a
   ctypes array of :class:`c_char`.

   If *size* is given (and not None), it must be an :cls:`int.
   It specifies the size of the returned array.

   If the *init* argument is given, it must be :cls:`bytes`. It is used
   to initialize the array items. Bytes not initialized this way are
   set to zero (NUL).

   If *size* is not given (or if it is None), the buffer is made one byte
   larger than *init*, effectively adding a NUL termination byte.

   If both arguments are given, *size* must not be less than ``len(init)``.

   .. warning::

      If *size* is equal to ``len(init)``, a NUL terminator is
      not added. Do not treat such a buffer as a C string.

   For example::

      >>> bytes(create_string_buffer(2))
      b'\x00\x00'

      >>> bytes(create_string_buffer(b'ab'))
      b'ab\x00'

      >>> bytes(create_string_buffer(b'ab', 2))
      b'ab'

      >>> bytes(create_string_buffer(b'ab', 4))
      b'ab\x00\x00'

      >>> bytes(create_string_buffer(b'abcdef', 2))
      Traceback (most recent call last):
         ...
      ValueError: byte string too long

# Conflicts:
#	Doc/library/ctypes.rst
@StanFromIreland
Copy link
Contributor Author

@encukou I have applied your suggested format.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Todo
Development

Successfully merging this pull request may close these issues.

3 participants