Skip to content

Commit 5ecaf25

Browse files
committed
bpo-32745: Fix a regression in the handling of ctypes' c_wchar_p type
Embedded nulls would cause a ValueError to be raised. Thanks go to Eryk Sun for their analysis.
1 parent cca4eec commit 5ecaf25

3 files changed

Lines changed: 13 additions & 1 deletion

File tree

Lib/ctypes/test/test_unicode.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ def test_buffers(self):
2626
self.assertEqual(buf[::2], 'a\xe4\xfc')
2727
self.assertEqual(buf[6:5:-1], "")
2828

29+
def test_embedded_null(self):
30+
class TestStruct(ctypes.Structure):
31+
_fields_ = [("unicode", ctypes.c_wchar_p)]
32+
t = TestStruct()
33+
# This would raise a ValueError.
34+
t.unicode = "foo\0bar\0\0"
35+
36+
2937
func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p
3038

3139
class StringTestCase(UnicodeTestCase):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a regression in the handling of ctypes' :data:`ctypes.c_wchar_p` type:
2+
embedded null characters would cause a :exc:`ValueError` to be raised. Patch
3+
by Zackery Spytz.

Modules/_ctypes/cfield.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1355,6 +1355,7 @@ Z_set(void *ptr, PyObject *value, Py_ssize_t size)
13551355
{
13561356
PyObject *keep;
13571357
wchar_t *buffer;
1358+
Py_ssize_t bsize;
13581359

13591360
if (value == Py_None) {
13601361
*(wchar_t **)ptr = NULL;
@@ -1378,7 +1379,7 @@ Z_set(void *ptr, PyObject *value, Py_ssize_t size)
13781379

13791380
/* We must create a wchar_t* buffer from the unicode object,
13801381
and keep it alive */
1381-
buffer = PyUnicode_AsWideCharString(value, NULL);
1382+
buffer = PyUnicode_AsWideCharString(value, &bsize);
13821383
if (!buffer)
13831384
return NULL;
13841385
keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor);

0 commit comments

Comments
 (0)