Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
gh-61103: use PEP 3118 codes in the ctypes
This change only buffer protocol support for complex types,
`_type_` properties aren't affected.
  • Loading branch information
skirpichev committed May 4, 2026
commit 92b6cbbfa1ae5b224441fd50ecbfb58f7b3a6b6f
9 changes: 9 additions & 0 deletions Lib/test/test_ctypes/test_pep3118.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ctypes
import re
import sys
import unittest
Expand Down Expand Up @@ -231,6 +232,14 @@ class Complete(Structure):

]

if hasattr(ctypes, 'c_float_complex'):
c_float_complex = ctypes.c_float_complex
c_double_complex = ctypes.c_double_complex
c_longdouble_complex = ctypes.c_longdouble_complex
native_types.extend([(c_float_complex * 4, "<Zf", (4,), c_float_complex),
(c_double_complex * 4, "<Zd", (4,), c_double_complex),
(c_longdouble_complex * 4, "<Zg", (4,), c_longdouble_complex)])


class BEPoint(BigEndianStructure):
_fields_ = [("x", c_long), ("y", c_long)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Use :pep:`3118` type codes for the buffer protocol support of complex types
in the :mod:`ctypes`. Patch by Sergey B Kirpichev.
25 changes: 23 additions & 2 deletions Modules/_ctypes/_ctypes.c
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ _ctypes_alloc_format_string_for_type(char code, int big_endian)
break;
}

result = PyMem_Malloc(3);
result = PyMem_Malloc(4);
if (result == NULL) {
PyErr_NoMemory();
return NULL;
Expand All @@ -320,6 +320,7 @@ _ctypes_alloc_format_string_for_type(char code, int big_endian)
result[0] = big_endian ? '>' : '<';
result[1] = pep_code;
result[2] = '\0';
result[3] = '\0';
return result;
}

Expand Down Expand Up @@ -3120,7 +3121,27 @@ PyCData_NewGetBuffer(PyObject *myself, Py_buffer *view, int flags)
view->len = self->b_size;
view->readonly = 0;
/* use default format character if not set */
view->format = info->format ? info->format : "B";
if (!info->format) {
view->format = "B";
}
else {
view->format = info->format;
if (view->format[1] == 'F') {
view->format[1] = 'Z';
view->format[2] = 'f';
view->format[3] = '\0';
}
if (view->format[1] == 'D') {
view->format[1] = 'Z';
view->format[2] = 'd';
view->format[3] = '\0';
}
if (view->format[1] == 'G') {
view->format[1] = 'Z';
view->format[2] = 'g';
view->format[3] = '\0';
}
}
view->ndim = info->ndim;
view->shape = info->shape;
view->itemsize = item_info->size;
Expand Down
Loading