diff --git a/Lib/ctypes/test/test_pointers.py b/Lib/ctypes/test/test_pointers.py index df62d04675b..05b180e62ac 100644 --- a/Lib/ctypes/test/test_pointers.py +++ b/Lib/ctypes/test/test_pointers.py @@ -175,5 +175,13 @@ class PointersTestCase(unittest.TestCase): self.assertRaises(TypeError, c_void_p, 3.14) # make sure floats are NOT accepted self.assertRaises(TypeError, c_void_p, object()) # nor other objects + def test_pointers_bool(self): + # NULL pointers have a boolean False value, non-NULL pointers True. + self.failUnlessEqual(bool(POINTER(c_int)()), False) + self.failUnlessEqual(bool(pointer(c_int())), True) + + self.failUnlessEqual(bool(CFUNCTYPE(None)(0)), False) + self.failUnlessEqual(bool(CFUNCTYPE(None)(42)), True) + if __name__ == '__main__': unittest.main() diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index fe332533a7a..b652319290b 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -474,7 +474,7 @@ GenericCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject * CDataType_from_buffer_copy(PyObject *type, PyObject *args) { - void *buffer; + const void *buffer; Py_ssize_t buffer_len; Py_ssize_t offset = 0; PyObject *obj, *result; @@ -3849,6 +3849,25 @@ CFuncPtr_repr(CFuncPtrObject *self) self); } +static int +Pointer_bool(CDataObject *self) +{ + return *(void **)self->b_ptr != NULL; +} + +static PyNumberMethods Pointer_as_number = { + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Pointer_bool, /* nb_bool */ +}; + PyTypeObject CFuncPtr_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_ctypes.CFuncPtr", @@ -3860,7 +3879,7 @@ PyTypeObject CFuncPtr_Type = { 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc)CFuncPtr_repr, /* tp_repr */ - 0, /* tp_as_number */ + &Pointer_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ @@ -4933,25 +4952,6 @@ static PyMappingMethods Pointer_as_mapping = { Pointer_subscript, }; -static int -Pointer_bool(CDataObject *self) -{ - return *(void **)self->b_ptr != NULL; -} - -static PyNumberMethods Pointer_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Pointer_bool, /* nb_bool */ -}; - PyTypeObject Pointer_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_ctypes._Pointer",