Skip to content

Commit 3e715e0

Browse files
gh-78878: Fix crash when creating an instance of _ctypes.CField (GH-14837)
(cherry picked from commit d713c54) Co-authored-by: Hai Shi <shihai1992@gmail.com>
1 parent 0397f04 commit 3e715e0

File tree

4 files changed

+10
-10
lines changed

4 files changed

+10
-10
lines changed

Lib/ctypes/test/test_struct_fields.py

+6
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ class X(Structure):
5454
x.char = b'a\0b\0'
5555
self.assertEqual(bytes(x), b'a\x00###')
5656

57+
def test_6(self):
58+
class X(Structure):
59+
_fields_ = [("x", c_int)]
60+
CField = type(X.x)
61+
self.assertRaises(TypeError, CField)
62+
5763
def test_gh99275(self):
5864
class BrokenStructure(Structure):
5965
def __init_subclass__(cls, **kwargs):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crash when creating an instance of :class:`!_ctypes.CField`.

Modules/_ctypes/cfield.c

+2-9
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,6 @@ static void pymem_destructor(PyObject *ptr)
3030
/*
3131
PyCField_Type
3232
*/
33-
static PyObject *
34-
PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
35-
{
36-
CFieldObject *obj;
37-
obj = (CFieldObject *)type->tp_alloc(type, 0);
38-
return (PyObject *)obj;
39-
}
4033

4134
/*
4235
* Expects the size, index and offset for the current field in *psize and
@@ -68,7 +61,7 @@ PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
6861
#define CONT_BITFIELD 2
6962
#define EXPAND_BITFIELD 3
7063

71-
self = (CFieldObject *)_PyObject_CallNoArgs((PyObject *)&PyCField_Type);
64+
self = (CFieldObject *)PyCField_Type.tp_alloc((PyTypeObject *)&PyCField_Type, 0);
7265
if (self == NULL)
7366
return NULL;
7467
dict = PyType_stgdict(desc);
@@ -343,7 +336,7 @@ PyTypeObject PyCField_Type = {
343336
0, /* tp_dictoffset */
344337
0, /* tp_init */
345338
0, /* tp_alloc */
346-
PyCField_new, /* tp_new */
339+
0, /* tp_new */
347340
0, /* tp_free */
348341
};
349342

Modules/_ctypes/stgdict.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ MakeFields(PyObject *type, CFieldObject *descr,
258258
}
259259
continue;
260260
}
261-
new_descr = (CFieldObject *)_PyObject_CallNoArgs((PyObject *)&PyCField_Type);
261+
new_descr = (CFieldObject *)PyCField_Type.tp_alloc((PyTypeObject *)&PyCField_Type, 0);
262262
if (new_descr == NULL) {
263263
Py_DECREF(fdescr);
264264
Py_DECREF(fieldlist);

0 commit comments

Comments
 (0)