[Python-3000-checkins] r56318 - in python/branches/py3k-struni: Lib/ctypes/test/test_bytes.py Modules/_ctypes/cfield.c

thomas.heller python-3000-checkins at python.org
Thu Jul 12 16:58:32 CEST 2007


Author: thomas.heller
Date: Thu Jul 12 16:58:32 2007
New Revision: 56318

Added:
   python/branches/py3k-struni/Lib/ctypes/test/test_bytes.py   (contents, props changed)
Modified:
   python/branches/py3k-struni/Modules/_ctypes/cfield.c
Log:
ctypes.c_char and ctypes.c_wchar now accept initialization from byte objects.

Added: python/branches/py3k-struni/Lib/ctypes/test/test_bytes.py
==============================================================================
--- (empty file)
+++ python/branches/py3k-struni/Lib/ctypes/test/test_bytes.py	Thu Jul 12 16:58:32 2007
@@ -0,0 +1,18 @@
+import unittest
+from ctypes import *
+
+class BytesTest(unittest.TestCase):
+    def test_c_char(self):
+        x = c_char(b"x")
+        x.value = b"y"
+        c_char.from_param(b"x")
+        (c_char * 3)(b"a", b"b", b"c")
+
+    def test_c_wchar(self):
+        x = c_wchar(b"x")
+        x.value = b"y"
+        c_wchar.from_param(b"x")
+        (c_wchar * 3)(b"a", b"b", b"c")
+
+if __name__ == '__main__':
+    unittest.main()

Modified: python/branches/py3k-struni/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/py3k-struni/Modules/_ctypes/cfield.c	(original)
+++ python/branches/py3k-struni/Modules/_ctypes/cfield.c	Thu Jul 12 16:58:32 2007
@@ -1141,6 +1141,27 @@
 static PyObject *
 c_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
+	if (PyUnicode_Check(value)) {
+		value = PyUnicode_AsEncodedString(value,
+						  conversion_mode_encoding,
+						  conversion_mode_errors);
+		if (value == NULL)
+			return NULL;
+		if (PyBytes_GET_SIZE(value) != 1) {
+			Py_DECREF(value);
+			PyErr_Format(PyExc_TypeError,
+				     "one character string expected");
+			return NULL;
+		}
+		*(char *)ptr = PyBytes_AsString(value)[0];
+		Py_DECREF(value);
+		_RET(value);
+	}
+	if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) {
+		*(char *)ptr = PyBytes_AsString(value)[0];
+		_RET(value);
+	}
+	/* XXX struni remove later */
 	if (!PyString_Check(value) || (1 != PyString_Size(value))) {
 		PyErr_Format(PyExc_TypeError,
 			     "one character string expected");
@@ -1154,6 +1175,7 @@
 static PyObject *
 c_get(void *ptr, Py_ssize_t size)
 {
+	/* XXX struni return PyBytes (or PyUnicode?) later */
 	return PyString_FromStringAndSize((char *)ptr, 1);
 }
 
@@ -1163,8 +1185,7 @@
 u_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	Py_ssize_t len;
-
-	if (PyString_Check(value)) {
+	if (PyBytes_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
 						    conversion_mode_encoding,
 						    conversion_mode_errors);


More information about the Python-3000-checkins mailing list