[Python-modules-commits] r942 - in /packages/ctypes/trunk: ./
ctypes/ ctypes/test/ ctypes/wrap/ docs/
docs/manual/ samples/ source/ source/darwin/ source/libffi/
source/libffi/include/ source/libffi/src/alpha/ source/libffi/src/frv/
source/libffi/src/powerpc/ source/libffi/src/x86/ source/libffi_arm_wince/
source/libffi_msvc/ wince/
rganesan at users.alioth.debian.org
rganesan at users.alioth.debian.org
Mon Jun 19 12:36:12 UTC 2006
Author: rganesan
Date: Mon Jun 19 12:36:05 2006
New Revision: 942
URL: http://svn.debian.org/wsvn/python-modules/?sc=1&rev=942
Log:
Imported new upstream.
Added:
packages/ctypes/trunk/ACKS
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ACKS
packages/ctypes/trunk/ANNOUNCE
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ANNOUNCE
packages/ctypes/trunk/ChangeLog
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ChangeLog
packages/ctypes/trunk/MANIFEST
- copied unchanged from r941, packages/ctypes/branches/upstream/current/MANIFEST
packages/ctypes/trunk/MANIFEST.in
- copied unchanged from r941, packages/ctypes/branches/upstream/current/MANIFEST.in
packages/ctypes/trunk/ctypes-dev.el
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ctypes-dev.el
packages/ctypes/trunk/ctypes/test/test_array_in_pointer.py
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ctypes/test/test_array_in_pointer.py
packages/ctypes/trunk/ctypes/test/test_find.py
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ctypes/test/test_find.py
packages/ctypes/trunk/ctypes/test/test_sizes.py
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ctypes/test/test_sizes.py
packages/ctypes/trunk/ctypes/test/test_unaligned_structures.py
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ctypes/test/test_unaligned_structures.py
packages/ctypes/trunk/ctypes/wintypes.py
- copied unchanged from r941, packages/ctypes/branches/upstream/current/ctypes/wintypes.py
packages/ctypes/trunk/docs/manual/
- copied from r941, packages/ctypes/branches/upstream/current/docs/manual/
packages/ctypes/trunk/source/ctypes_dlfcn.h
- copied unchanged from r941, packages/ctypes/branches/upstream/current/source/ctypes_dlfcn.h
packages/ctypes/trunk/source/libffi_arm_wince/
- copied from r941, packages/ctypes/branches/upstream/current/source/libffi_arm_wince/
packages/ctypes/trunk/source/libffi_msvc/
- copied from r941, packages/ctypes/branches/upstream/current/source/libffi_msvc/
packages/ctypes/trunk/wince/
- copied from r941, packages/ctypes/branches/upstream/current/wince/
Removed:
packages/ctypes/trunk/MANIFEST.other.in
packages/ctypes/trunk/NEWS.txt
packages/ctypes/trunk/ctypes/_loader.py
packages/ctypes/trunk/ctypes/decorators.py
packages/ctypes/trunk/ctypes/test/test_codegen.py
packages/ctypes/trunk/ctypes/test/test_leaks.py
packages/ctypes/trunk/ctypes/test/test_posix.py
packages/ctypes/trunk/ctypes/wrap/
packages/ctypes/trunk/docs/changes.stx
packages/ctypes/trunk/docs/default.css
packages/ctypes/trunk/docs/faq.stx
packages/ctypes/trunk/docs/index.stx
packages/ctypes/trunk/docs/internals.stx
packages/ctypes/trunk/docs/reference.stx
packages/ctypes/trunk/docs/tutorial.stx
packages/ctypes/trunk/run_remote_test.py
packages/ctypes/trunk/samples/
Modified:
packages/ctypes/trunk/LICENSE.txt
packages/ctypes/trunk/PKG-INFO
packages/ctypes/trunk/ctypes/.CTYPES_DEVEL
packages/ctypes/trunk/ctypes/__init__.py
packages/ctypes/trunk/ctypes/_endian.py
packages/ctypes/trunk/ctypes/test/__init__.py
packages/ctypes/trunk/ctypes/test/test_bitfields.py
packages/ctypes/trunk/ctypes/test/test_buffers.py
packages/ctypes/trunk/ctypes/test/test_byteswap.py
packages/ctypes/trunk/ctypes/test/test_callbacks.py
packages/ctypes/trunk/ctypes/test/test_cast.py
packages/ctypes/trunk/ctypes/test/test_cfuncs.py
packages/ctypes/trunk/ctypes/test/test_checkretval.py
packages/ctypes/trunk/ctypes/test/test_funcptr.py
packages/ctypes/trunk/ctypes/test/test_functions.py
packages/ctypes/trunk/ctypes/test/test_keeprefs.py
packages/ctypes/trunk/ctypes/test/test_libc.py
packages/ctypes/trunk/ctypes/test/test_loading.py
packages/ctypes/trunk/ctypes/test/test_macholib.py
packages/ctypes/trunk/ctypes/test/test_numbers.py
packages/ctypes/trunk/ctypes/test/test_parameters.py
packages/ctypes/trunk/ctypes/test/test_pointers.py
packages/ctypes/trunk/ctypes/test/test_prototypes.py
packages/ctypes/trunk/ctypes/test/test_random_things.py
packages/ctypes/trunk/ctypes/test/test_refcounts.py
packages/ctypes/trunk/ctypes/test/test_repr.py
packages/ctypes/trunk/ctypes/test/test_returnfuncptrs.py
packages/ctypes/trunk/ctypes/test/test_slicing.py
packages/ctypes/trunk/ctypes/test/test_stringptr.py
packages/ctypes/trunk/ctypes/test/test_strings.py
packages/ctypes/trunk/ctypes/test/test_structures.py
packages/ctypes/trunk/ctypes/test/test_unicode.py
packages/ctypes/trunk/ctypes/test/test_values.py
packages/ctypes/trunk/ctypes/test/test_win32.py
packages/ctypes/trunk/ctypes/util.py
packages/ctypes/trunk/setup.py
packages/ctypes/trunk/source/_ctypes.c
packages/ctypes/trunk/source/_ctypes_test.c
packages/ctypes/trunk/source/callbacks.c
packages/ctypes/trunk/source/callproc.c
packages/ctypes/trunk/source/cfield.c
packages/ctypes/trunk/source/ctypes.h
packages/ctypes/trunk/source/darwin/dlfcn.h
packages/ctypes/trunk/source/darwin/dlfcn_simple.c
packages/ctypes/trunk/source/libffi/configure
packages/ctypes/trunk/source/libffi/configure.ac
packages/ctypes/trunk/source/libffi/fficonfig.py.in
packages/ctypes/trunk/source/libffi/include/ffi.h.in
packages/ctypes/trunk/source/libffi/src/alpha/osf.S
packages/ctypes/trunk/source/libffi/src/frv/eabi.S
packages/ctypes/trunk/source/libffi/src/powerpc/darwin_closure.S
packages/ctypes/trunk/source/libffi/src/x86/ffi.c
packages/ctypes/trunk/source/stgdict.c
Modified: packages/ctypes/trunk/LICENSE.txt
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/LICENSE.txt?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/LICENSE.txt (original)
+++ packages/ctypes/trunk/LICENSE.txt Mon Jun 19 12:36:05 2006
@@ -1,4 +1,4 @@
- Copyright (c) 2000, 2001, 2002, 2003, 2004 Thomas Heller
+ Copyright (c) 2000 - 2006 Thomas Heller
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
Modified: packages/ctypes/trunk/PKG-INFO
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/PKG-INFO?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/PKG-INFO (original)
+++ packages/ctypes/trunk/PKG-INFO Mon Jun 19 12:36:05 2006
@@ -1,6 +1,6 @@
Metadata-Version: 1.0
Name: ctypes
-Version: 0.9.9.3
+Version: 0.9.9.6
Summary: create and manipulate C data types in Python, call functions in shared libraries
Home-page: http://starship.python.net/crew/theller/ctypes.html
Author: Thomas Heller
Modified: packages/ctypes/trunk/ctypes/.CTYPES_DEVEL
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/.CTYPES_DEVEL?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/.CTYPES_DEVEL (original)
+++ packages/ctypes/trunk/ctypes/.CTYPES_DEVEL Mon Jun 19 12:36:05 2006
@@ -1,13 +1,6 @@
# -*- python -*-
def install():
import sys, os
-
- p = os.path.abspath(
- os.path.join(os.path.dirname(__file__), "..", sys.platform))
- try:
- __path__.insert(0, p)
- except NameError:
- pass # when ctypes/__init__.py is imported *not* as package
from distutils.util import get_platform
plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
Modified: packages/ctypes/trunk/ctypes/__init__.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/__init__.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/__init__.py (original)
+++ packages/ctypes/trunk/ctypes/__init__.py Mon Jun 19 12:36:05 2006
@@ -1,26 +1,23 @@
"""create and manipulate C data types in Python"""
+
+import os as _os, sys as _sys
+from itertools import chain as _chain
# special developer support to use ctypes from the CVS sandbox,
# without installing it
-import os as _os, sys as _sys
-from itertools import chain as _chain
-
+# XXX Remove this for the python core version
_magicfile = _os.path.join(_os.path.dirname(__file__), ".CTYPES_DEVEL")
if _os.path.isfile(_magicfile):
execfile(_magicfile)
del _magicfile
-__version__ = "0.9.9.3"
+__version__ = "0.9.9.6"
from _ctypes import Union, Structure, Array
from _ctypes import _Pointer
from _ctypes import CFuncPtr as _CFuncPtr
from _ctypes import __version__ as _ctypes_version
-try:
- from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
-except (ImportError, AttributeError):
- RTLD_GLOBAL = RTLD_LOCAL = None
-
+from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
from _ctypes import ArgumentError
from struct import calcsize as _calcsize
@@ -33,8 +30,6 @@
from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \
FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI
-
-from ctypes._loader import LibraryLoader
"""
WINOLEAPI -> HRESULT
@@ -76,16 +71,18 @@
_c_functype_cache = {}
def CFUNCTYPE(restype, *argtypes):
"""CFUNCTYPE(restype, *argtypes) -> function prototype.
-
+
restype: the result type
argtypes: a sequence specifying the argument types
-
+
The function prototype can be called in three ways to create a
callable object:
-
- prototype(funct) - returns a C callable function calling funct
- prototype(vtbl_index, method_name[, paramflags]) - a Python callable that calls a COM method
- prototype(funct_name, dll[, paramflags]) - a Python callable that calls an exported function in a dll
+
+ prototype(integer address) -> foreign function
+ prototype(callable) -> create and return a C callable function from callable
+ prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method
+ prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal
+ prototype((function name, dll object)[, paramflags]) -> foreign function exported by name
"""
try:
return _c_functype_cache[(restype, argtypes)]
@@ -99,8 +96,7 @@
if _os.name in ("nt", "ce"):
from _ctypes import LoadLibrary as _dlopen
- from _ctypes import FUNCFLAG_HRESULT as _FUNCFLAG_HRESULT, \
- FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
+ from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
if _os.name == "ce":
# 'ce' doesn't have the stdcall calling convention
_FUNCFLAG_STDCALL = _FUNCFLAG_CDECL
@@ -140,7 +136,7 @@
class c_ulong(_SimpleCData):
_type_ = "L"
-
+
if _calcsize("i") == _calcsize("l"):
# if int and long have the same size, make c_int an alias for c_long
c_int = c_long
@@ -154,7 +150,7 @@
class c_float(_SimpleCData):
_type_ = "f"
-
+
class c_double(_SimpleCData):
_type_ = "d"
@@ -312,10 +308,11 @@
raise AttributeError, name
return self.__getitem__(name)
- def __getitem__(self, name):
- func = self._FuncPtr(name, self)
- func.__name__ = name
- setattr(self, name, func)
+ def __getitem__(self, name_or_ordinal):
+ func = self._FuncPtr((name_or_ordinal, self))
+ if not isinstance(name_or_ordinal, (int, long)):
+ func.__name__ = name_or_ordinal
+ setattr(self, name_or_ordinal, func)
return func
class PyDLL(CDLL):
@@ -328,7 +325,7 @@
_restype_ = c_int # default, can be overridden in instances
if _os.name in ("nt", "ce"):
-
+
class WinDLL(CDLL):
"""This class represents a dll exporting functions using the
Windows stdcall calling convention.
@@ -352,7 +349,7 @@
# doesn't have a way to raise an exception in the caller's
# frame).
_check_retval_ = _check_HRESULT
-
+
class OleDLL(CDLL):
"""This class represents a dll exporting functions using the
Windows stdcall calling convention, and returning HRESULT.
@@ -360,12 +357,25 @@
exceptions.
"""
class _FuncPtr(_CFuncPtr):
- # It would be possible to remove the _FUNCFLAG_HRESULT
- # code, and use HRESULT as _restype_. But
- # _FUNCFLAG_HRESULT is used in other places in the C code
- # as well, so we leave it as it is.
- _flags_ = _FUNCFLAG_STDCALL | _FUNCFLAG_HRESULT
- _restype_ = c_int # needed, but unused (see _FUNCFLAG_HRESULT flag)
+ _flags_ = _FUNCFLAG_STDCALL
+ _restype_ = HRESULT
+
+class LibraryLoader(object):
+ def __init__(self, dlltype):
+ self._dlltype = dlltype
+
+ def __getattr__(self, name):
+ if name[0] == '_':
+ raise AttributeError(name)
+ dll = self._dlltype(name)
+ setattr(self, name, dll)
+ return dll
+
+ def __getitem__(self, name):
+ return getattr(self, name)
+
+ def LoadLibrary(self, name):
+ return self._dlltype(name)
cdll = LibraryLoader(CDLL)
pydll = LibraryLoader(PyDLL)
@@ -396,20 +406,33 @@
_pointer_type_cache[None] = c_void_p
-# functions
-
-from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, cast
-
if sizeof(c_uint) == sizeof(c_void_p):
c_size_t = c_uint
elif sizeof(c_ulong) == sizeof(c_void_p):
c_size_t = c_ulong
+# functions
+
+from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr
+
## void *memmove(void *, const void *, size_t);
memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr)
## void *memset(void *, int, size_t)
memset = CFUNCTYPE(c_void_p, c_void_p, c_int, c_size_t)(_memset_addr)
+
+def PYFUNCTYPE(restype, *argtypes):
+ class CFunctionType(_CFuncPtr):
+ _argtypes_ = argtypes
+ _restype_ = restype
+ _flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
+ return CFunctionType
+_cast = PYFUNCTYPE(py_object, c_void_p, py_object)(_cast_addr)
+
+def cast(obj, typ):
+ result = _cast(obj, typ)
+ result.__keepref = obj
+ return result
_string_at = CFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
def string_at(ptr, size=0):
@@ -429,11 +452,7 @@
Return the string at addr."""
return _wstring_at(ptr, size)
-
-
-from decorators import cdecl
-if _os.name == "nt":
- from decorators import stdcall
+
if _os.name == "nt": # COM stuff
def DllGetClassObject(rclsid, riid, ppv):
@@ -483,3 +502,16 @@
return result
from ctypes._endian import BigEndianStructure, LittleEndianStructure
+
+# Fill in specifically-sized types
+c_int8 = c_byte
+c_uint8 = c_ubyte
+for kind in [c_short, c_int, c_long, c_longlong]:
+ if sizeof(kind) == 2: c_int16 = kind
+ elif sizeof(kind) == 4: c_int32 = kind
+ elif sizeof(kind) == 8: c_int64 = kind
+for kind in [c_ushort, c_uint, c_ulong, c_ulonglong]:
+ if sizeof(kind) == 2: c_uint16 = kind
+ elif sizeof(kind) == 4: c_uint32 = kind
+ elif sizeof(kind) == 8: c_uint64 = kind
+del(kind)
Modified: packages/ctypes/trunk/ctypes/_endian.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/_endian.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/_endian.py (original)
+++ packages/ctypes/trunk/ctypes/_endian.py Mon Jun 19 12:36:05 2006
@@ -55,4 +55,3 @@
else:
raise RuntimeError("Invalid byteorder")
-
Modified: packages/ctypes/trunk/ctypes/test/__init__.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/__init__.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/__init__.py (original)
+++ packages/ctypes/trunk/ctypes/test/__init__.py Mon Jun 19 12:36:05 2006
@@ -83,7 +83,7 @@
ptc = ctypes._pointer_type_cache.copy()
cfc = ctypes._c_functype_cache.copy()
wfc = ctypes._win_functype_cache.copy()
-
+
# when searching for refcount leaks, we have to manually reset any
# caches that ctypes has.
def cleanup():
Modified: packages/ctypes/trunk/ctypes/test/test_bitfields.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_bitfields.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_bitfields.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_bitfields.py Mon Jun 19 12:36:05 2006
@@ -15,7 +15,7 @@
("G", c_int, 7),
("H", c_int, 8),
("I", c_int, 9),
-
+
("M", c_short, 1),
("N", c_short, 2),
("O", c_short, 3),
@@ -24,7 +24,7 @@
("R", c_short, 6),
("S", c_short, 7)]
-func = cdll.load(_ctypes_test.__file__).unpack_bitfields
+func = CDLL(_ctypes_test.__file__).unpack_bitfields
func.argtypes = POINTER(BITS), c_char
##for n in "ABCDEFGHIMNOPQRS":
@@ -62,7 +62,7 @@
x = X()
x.a, x.b, x.c = -1, 7, -1
self.failUnlessEqual((x.a, x.b, x.c), (-1, 7, -1))
-
+
def test_ulonglong(self):
class X(Structure):
_fields_ = [("a", c_ulonglong, 1),
@@ -79,7 +79,7 @@
for c_typ in signed_int_types:
class X(Structure):
_fields_ = [("dummy", c_typ),
- ("a", c_typ, 3),
+ ("a", c_typ, 3),
("b", c_typ, 3),
("c", c_typ, 1)]
self.failUnlessEqual(sizeof(X), sizeof(c_typ)*2)
Modified: packages/ctypes/trunk/ctypes/test/test_buffers.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_buffers.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_buffers.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_buffers.py Mon Jun 19 12:36:05 2006
@@ -8,14 +8,14 @@
self.failUnlessEqual(len(b), 32)
self.failUnlessEqual(sizeof(b), 32 * sizeof(c_char))
self.failUnless(type(b[0]) is str)
-
+
b = create_string_buffer("abc")
self.failUnlessEqual(len(b), 4) # trailing nul char
self.failUnlessEqual(sizeof(b), 4 * sizeof(c_char))
self.failUnless(type(b[0]) is str)
self.failUnlessEqual(b[0], "a")
self.failUnlessEqual(b[:], "abc\0")
-
+
def test_string_conversion(self):
b = create_string_buffer(u"abc")
self.failUnlessEqual(len(b), 4) # trailing nul char
Modified: packages/ctypes/trunk/ctypes/test/test_byteswap.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_byteswap.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_byteswap.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_byteswap.py Mon Jun 19 12:36:05 2006
@@ -11,11 +11,11 @@
# byte order, and a __ctype_le__ attribute that is the same type in
# LITTLE ENDIAN byte order.
#
-# For Structures and Unions, these types are created on demand.
+# For Structures and Unions, these types are created on demand.
class Test(unittest.TestCase):
def X_test(self):
- print sys.byteorder
+ print >> sys.stderr, sys.byteorder
for i in range(32):
bits = BITS()
setattr(bits, "i%s" % i, 1)
@@ -149,7 +149,7 @@
self.failUnless(c_char.__ctype_le__ is c_char)
self.failUnless(c_char.__ctype_be__ is c_char)
- def test_struct_fields(self):
+ def test_struct_fields_1(self):
if sys.byteorder == "little":
base = BigEndianStructure
else:
@@ -198,16 +198,20 @@
pass
self.assertRaises(TypeError, setattr, S, "_fields_", [("s", T)])
- def test_struct_fields(self):
- if sys.byteorder == "little":
- base = BigEndianStructure
- fmt = ">bhid"
- else:
- base = LittleEndianStructure
- fmt = "<bhid"
+ def test_struct_fields_2(self):
+ # standard packing in struct uses no alignment.
+ # So, we have to align using pad bytes.
+ #
+ # Unaligned accesses will crash Python (on those platforms that
+ # don't allow it, like sparc solaris).
+ if sys.byteorder == "little":
+ base = BigEndianStructure
+ fmt = ">bxhid"
+ else:
+ base = LittleEndianStructure
+ fmt = "<bxhid"
class S(base):
- _pack_ = 1 # struct with '<' or '>' uses standard alignment.
_fields_ = [("b", c_byte),
("h", c_short),
("i", c_int),
@@ -217,5 +221,60 @@
s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)
self.failUnlessEqual(bin(s1), bin(s2))
+ def test_unaligned_nonnative_struct_fields(self):
+ if sys.byteorder == "little":
+ base = BigEndianStructure
+ fmt = ">b h xi xd"
+ else:
+ base = LittleEndianStructure
+ fmt = "<b h xi xd"
+
+ class S(base):
+ _pack_ = 1
+ _fields_ = [("b", c_byte),
+
+ ("h", c_short),
+
+ ("_1", c_byte),
+ ("i", c_int),
+
+ ("_2", c_byte),
+ ("d", c_double)]
+
+ s1 = S()
+ s1.b = 0x12
+ s1.h = 0x1234
+ s1.i = 0x12345678
+ s1.d = 3.14
+ s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)
+ self.failUnlessEqual(bin(s1), bin(s2))
+
+ def test_unaligned_native_struct_fields(self):
+ if sys.byteorder == "little":
+ fmt = "<b h xi xd"
+ else:
+ base = LittleEndianStructure
+ fmt = ">b h xi xd"
+
+ class S(Structure):
+ _pack_ = 1
+ _fields_ = [("b", c_byte),
+
+ ("h", c_short),
+
+ ("_1", c_byte),
+ ("i", c_int),
+
+ ("_2", c_byte),
+ ("d", c_double)]
+
+ s1 = S()
+ s1.b = 0x12
+ s1.h = 0x1234
+ s1.i = 0x12345678
+ s1.d = 3.14
+ s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)
+ self.failUnlessEqual(bin(s1), bin(s2))
+
if __name__ == "__main__":
unittest.main()
Modified: packages/ctypes/trunk/ctypes/test/test_callbacks.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_callbacks.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_callbacks.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_callbacks.py Mon Jun 19 12:36:05 2006
@@ -3,7 +3,7 @@
import _ctypes_test
class Callbacks(unittest.TestCase):
- functype = CFUNCTYPE
+ functype = CFUNCTYPE
## def tearDown(self):
## import gc
@@ -29,21 +29,6 @@
else:
self.failUnlessEqual(self.got_args, (-3, arg))
self.failUnlessEqual(result, arg)
-
- if not hasattr(unittest.TestCase, "failUnlessAlmostEqual"):
- # This method is not present in Python 2.2
- # Copied from Python 2.3
- def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
- """Fail if the two objects are unequal as determined by their
- difference rounded to the given number of decimal places
- (default 7) and comparing to zero.
-
- Note that decimal places (from zero) is usually not the same
- as significant digits (measured from the most signficant digit).
- """
- if round(second-first, places) != 0:
- raise self.failureException, \
- (msg or '%s != %s within %s places' % (`first`, `second`, `places` ))
################
@@ -96,9 +81,25 @@
self.check_type(c_char, "x")
self.check_type(c_char, "a")
- def test_char_p(self):
- self.check_type(c_char_p, "abc")
- self.check_type(c_char_p, "def")
+ # disabled: would now (correctly) raise a RuntimeWarning about
+ # a memory leak. A callback function cannot return a non-integral
+ # C type without causing a memory leak.
+## def test_char_p(self):
+## self.check_type(c_char_p, "abc")
+## self.check_type(c_char_p, "def")
+
+ def test_pyobject(self):
+ o = ()
+ from sys import getrefcount as grc
+ for o in (), [], object():
+ initial = grc(o)
+ # This call leaks a reference to 'o'...
+ self.check_type(py_object, o)
+ before = grc(o)
+ # ...but this call doesn't leak any more. Where is the refcount?
+ self.check_type(py_object, o)
+ after = grc(o)
+ self.failUnlessEqual((after, o), (before, o))
try:
WINFUNCTYPE
@@ -114,7 +115,7 @@
def test_integrate(self):
# Derived from some then non-working code, posted by David Foster
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
# The function prototype called by 'integrate': double func(double);
CALLBACK = CFUNCTYPE(c_double, c_double)
@@ -129,7 +130,7 @@
result = integrate(0.0, 1.0, CALLBACK(func), 10)
diff = abs(result - 1./3.)
-
+
self.failUnless(diff < 0.01, "%s not less than 0.01" % diff)
################################################################
Modified: packages/ctypes/trunk/ctypes/test/test_cast.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_cast.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_cast.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_cast.py Mon Jun 19 12:36:05 2006
@@ -23,33 +23,24 @@
def test_address2pointer(self):
array = (c_int * 3)(42, 17, 2)
- # on AMD64, sizeof(int) == 4 and sizeof(void *) == 8.
- # By default, cast would convert a Python int (or long) into
- # a C int, which would be too short to represent a pointer
- # on this platform.
-
- # So we have to wrap the address into a c_void_p for this to work.
- #
- # XXX Better would be to hide the differences in the cast function.
address = addressof(array)
ptr = cast(c_void_p(address), POINTER(c_int))
+ self.failUnlessEqual([ptr[i] for i in range(3)], [42, 17, 2])
+
+ ptr = cast(address, POINTER(c_int))
self.failUnlessEqual([ptr[i] for i in range(3)], [42, 17, 2])
def test_ptr2array(self):
array = (c_int * 3)(42, 17, 2)
-## # Hm, already tested above.
-## ptr = cast(array, POINTER(c_int))
-## self.failUnlessEqual([ptr[i] for i in range(3)], [42, 17, 2])
+ from sys import getrefcount
-# print cast(addressof(array), c_int * 3)[:]
-## ptr = cast(addressof(ptr)
-
-## print ptr[0], ptr[1], ptr[2]
-## ptr = POINTER(c_int).from_address(addressof(array))
-## # XXX this crashes:
-## print ptr[0], ptr[1], ptr[2]
+ before = getrefcount(array)
+ ptr = cast(array, POINTER(c_int))
+ self.failUnlessEqual(getrefcount(array), before + 1)
+ del ptr
+ self.failUnlessEqual(getrefcount(array), before)
if __name__ == "__main__":
unittest.main()
Modified: packages/ctypes/trunk/ctypes/test/test_cfuncs.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_cfuncs.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_cfuncs.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_cfuncs.py Mon Jun 19 12:36:05 2006
@@ -7,7 +7,7 @@
import _ctypes_test
class CFunctions(unittest.TestCase):
- _dll = cdll.load(_ctypes_test.__file__)
+ _dll = CDLL(_ctypes_test.__file__)
def S(self):
return c_longlong.in_dll(self._dll, "last_tf_arg_s").value
@@ -179,7 +179,7 @@
def __getattr__(self, name):
if name[:2] == '__' and name[-2:] == '__':
raise AttributeError, name
- func = self._FuncPtr("s_" + name, self)
+ func = self._FuncPtr(("s_" + name, self))
setattr(self, name, func)
return func
Modified: packages/ctypes/trunk/ctypes/test/test_checkretval.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_checkretval.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_checkretval.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_checkretval.py Mon Jun 19 12:36:05 2006
@@ -3,18 +3,18 @@
from ctypes import *
+class CHECKED(c_int):
+ def _check_retval_(value):
+ # Receives a CHECKED instance.
+ return str(value.value)
+ _check_retval_ = staticmethod(_check_retval_)
+
class Test(unittest.TestCase):
def test_checkretval(self):
- class CHECKED(c_int):
- def _check_retval_(value):
- # Receives a CHECKED instance.
- return str(value.value)
- _check_retval_ = staticmethod(_check_retval_)
-
import _ctypes_test
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
self.failUnlessEqual(42, dll._testfunc_p_p(42))
dll._testfunc_p_p.restype = CHECKED
Modified: packages/ctypes/trunk/ctypes/test/test_funcptr.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_funcptr.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_funcptr.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_funcptr.py Mon Jun 19 12:36:05 2006
@@ -8,7 +8,7 @@
WINFUNCTYPE = CFUNCTYPE
import _ctypes_test
-lib = cdll.load(_ctypes_test.__file__)
+lib = CDLL(_ctypes_test.__file__)
class CFuncPtrTestCase(unittest.TestCase):
def test_basic(self):
@@ -122,6 +122,6 @@
self.failUnlessEqual(strtok(None, "\n"), "b")
self.failUnlessEqual(strtok(None, "\n"), "c")
self.failUnlessEqual(strtok(None, "\n"), None)
-
+
if __name__ == '__main__':
unittest.main()
Modified: packages/ctypes/trunk/ctypes/test/test_functions.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_functions.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_functions.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_functions.py Mon Jun 19 12:36:05 2006
@@ -15,9 +15,12 @@
WINFUNCTYPE = CFUNCTYPE
import _ctypes_test
-dll = cdll.load(_ctypes_test.__file__)
+dll = CDLL(_ctypes_test.__file__)
if sys.platform == "win32":
- windll = windll.load(_ctypes_test.__file__)
+ windll = WinDLL(_ctypes_test.__file__)
+
+class POINT(Structure):
+ _fields_ = [("x", c_int), ("y", c_int)]
class FunctionTestCase(unittest.TestCase):
@@ -28,14 +31,14 @@
# But in early versions of _ctypes.c, the result of tp_new
# wasn't checked, and it even crashed Python.
# Found by Greg Chapman.
-
+
try:
class X(object, Array):
_length_ = 5
_type_ = "i"
except TypeError:
pass
-
+
from _ctypes import _Pointer
try:
@@ -91,6 +94,7 @@
def test_intresult(self):
f = dll._testfunc_i_bhilfd
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
+ f.restype = c_int
result = f(1, 2, 3, 4, 5.0, 6.0)
self.failUnlessEqual(result, 21)
self.failUnlessEqual(type(result), int)
@@ -105,7 +109,7 @@
result = f(1, 2, 3, 4, 5.0, 6.0)
self.failUnlessEqual(result, 21)
self.failUnlessEqual(type(result), int)
-
+
result = f(1, 2, 3, 0x10004, 5.0, 6.0)
self.failUnlessEqual(result, 21)
self.failUnlessEqual(type(result), int)
@@ -124,7 +128,7 @@
result = f(-1, -2, -3, -4, -5.0, -6.0)
self.failUnlessEqual(result, -21)
self.failUnlessEqual(type(result), float)
-
+
def test_doubleresult(self):
f = dll._testfunc_d_bhilfd
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
@@ -136,7 +140,7 @@
result = f(-1, -2, -3, -4, -5.0, -6.0)
self.failUnlessEqual(result, -21)
self.failUnlessEqual(type(result), float)
-
+
def test_longlongresult(self):
try:
c_longlong
@@ -226,7 +230,7 @@
self.failUnlessEqual(args, expected)
################################################################
-
+
def test_callbacks(self):
f = dll._testfunc_callback_i_if
@@ -237,7 +241,7 @@
def callback(value):
#print "called back with", value
return value
-
+
cb = MyCallback(callback)
result = f(-10, cb)
self.failUnlessEqual(result, -18)
@@ -247,7 +251,7 @@
cb = MyCallback(callback)
result = f(-10, cb)
self.failUnlessEqual(result, -18)
-
+
AnotherCallback = WINFUNCTYPE(c_int, c_int, c_int, c_int, c_int)
# check that the prototype works: we call f with wrong
@@ -271,7 +275,7 @@
#print "called back with", value
self.failUnlessEqual(type(value), int)
return value
-
+
cb = MyCallback(callback)
result = f(-10, cb)
self.failUnlessEqual(result, -18)
@@ -298,9 +302,6 @@
self.assertRaises(ValueError, c_int.in_dll, dll, "_xxx_yyy")
def test_byval(self):
-
- class POINT(Structure):
- _fields_ = [("x", c_int), ("y", c_int)]
# without prototype
ptin = POINT(1, 2)
Modified: packages/ctypes/trunk/ctypes/test/test_keeprefs.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_keeprefs.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_keeprefs.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_keeprefs.py Mon Jun 19 12:36:05 2006
@@ -130,7 +130,7 @@
("b", POINTER(POINT))]
r = RECT()
p1 = POINT(1, 2)
-
+
r.a = pointer(p1)
r.b = pointer(p1)
## from pprint import pprint as pp
@@ -140,5 +140,10 @@
r.a[0].x = 42
r.a[0].y = 99
+ # to avoid leaking when tests are run several times
+ # clean up the types left in the cache.
+ from ctypes import _pointer_type_cache
+ del _pointer_type_cache[POINT]
+
if __name__ == "__main__":
unittest.main()
Modified: packages/ctypes/trunk/ctypes/test/test_libc.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_libc.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_libc.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_libc.py Mon Jun 19 12:36:05 2006
@@ -4,7 +4,7 @@
from ctypes import *
import _ctypes_test
-lib = cdll.load(_ctypes_test.__file__)
+lib = CDLL(_ctypes_test.__file__)
class LibTest(unittest.TestCase):
def test_sqrt(self):
Modified: packages/ctypes/trunk/ctypes/test/test_loading.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_loading.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_loading.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_loading.py Mon Jun 19 12:36:05 2006
@@ -1,41 +1,84 @@
from ctypes import *
import sys, unittest
import os, StringIO
+from ctypes.util import find_library
+from ctypes.test import is_resource_enabled
+
+libc_name = None
+if os.name == "nt":
+ libc_name = "msvcrt"
+elif os.name == "ce":
+ libc_name = "coredll"
+elif sys.platform == "darwin":
+ libc_name = "libc.dylib"
+elif sys.platform == "cygwin":
+ libc_name = "cygwin1.dll"
+else:
+ for line in os.popen("ldd %s" % sys.executable):
+ if "libc.so" in line:
+ if sys.platform == "openbsd3":
+ libc_name = line.split()[4]
+ else:
+ libc_name = line.split()[2]
+ break
+
+if is_resource_enabled("printing"):
+ print "libc_name is", libc_name
class LoaderTest(unittest.TestCase):
unknowndll = "xxrandomnamexx"
- def test_load(self):
- if os.name == "nt":
- name = "msvcrt"
- elif os.name == "ce":
- name = "coredll"
- elif sys.platform == "darwin":
- name = "libc.dylib"
- elif sys.platform.startswith("freebsd"):
- name = "libc.so"
- elif sys.platform == "sunos5":
- name = "libc.so"
- else:
- name = "libc.so.6"
- cdll.load(name)
- self.assertRaises(OSError, cdll.load, self.unknowndll)
+ if libc_name is not None:
+ def test_load(self):
+ CDLL(libc_name)
+ CDLL(os.path.basename(libc_name))
+ self.assertRaises(OSError, CDLL, self.unknowndll)
- def test_load_version(self):
- version = "6"
- name = "c"
- if sys.platform == "linux2":
- cdll.load_version(name, version)
+ if libc_name is not None and os.path.basename(libc_name) == "libc.so.6":
+ def test_load_version(self):
+ cdll.LoadLibrary("libc.so.6")
# linux uses version, libc 9 should not exist
- self.assertRaises(OSError, cdll.load_version, name, "9")
- self.assertRaises(OSError, cdll.load_version, self.unknowndll, "")
+ self.assertRaises(OSError, cdll.LoadLibrary, "libc.so.9")
+ self.assertRaises(OSError, cdll.LoadLibrary, self.unknowndll)
- if os.name == "posix" and sys.platform != "sunos5":
- def test_find(self):
- name = "c"
- cdll.find(name)
- self.assertRaises(OSError, cdll.find, self.unknowndll)
+ def test_find(self):
+ for name in ("c", "m"):
+ lib = find_library(name)
+ if lib:
+ cdll.LoadLibrary(lib)
+ CDLL(lib)
+
+ if os.name in ("nt", "ce"):
+ def test_load_library(self):
+ print find_library("kernel32")
+ print find_library("user32")
+
+ if os.name == "nt":
+ windll.kernel32.GetModuleHandleW
+ windll["kernel32"].GetModuleHandleW
+ windll.LoadLibrary("kernel32").GetModuleHandleW
+ WinDLL("kernel32").GetModuleHandleW
+ elif os.name == "ce":
+ windll.coredll.GetModuleHandleW
+ windll["coredll"].GetModuleHandleW
+ windll.LoadLibrary("coredll").GetModuleHandleW
+ WinDLL("coredll").GetModuleHandleW
+
+ def test_load_ordinal_functions(self):
+ import _ctypes_test
+ dll = WinDLL(_ctypes_test.__file__)
+ # We load the same function both via ordinal and name
+ func_ord = dll[2]
+ func_name = dll.GetString
+ # addressof gets the address where the function pointer is stored
+ a_ord = addressof(func_ord)
+ a_name = addressof(func_name)
+ f_ord_addr = c_void_p.from_address(a_ord).value
+ f_name_addr = c_void_p.from_address(a_name).value
+ self.failUnlessEqual(hex(f_ord_addr), hex(f_name_addr))
+
+ self.failUnlessRaises(AttributeError, dll.__getitem__, 1234)
if __name__ == "__main__":
unittest.main()
Modified: packages/ctypes/trunk/ctypes/test/test_macholib.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_macholib.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_macholib.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_macholib.py Mon Jun 19 12:36:05 2006
@@ -36,13 +36,13 @@
from ctypes.macholib.dyld import dyld_find
def find_lib(name):
- possible = ['lib'+name+'.dylib', name+'.dylib', name+'.framework/'+name]
- for dylib in possible:
- try:
- return os.path.realpath(dyld_find(dylib))
- except ValueError:
- pass
- raise ValueError, "%s not found" % (name,)
+ possible = ['lib'+name+'.dylib', name+'.dylib', name+'.framework/'+name]
+ for dylib in possible:
+ try:
+ return os.path.realpath(dyld_find(dylib))
+ except ValueError:
+ pass
+ raise ValueError, "%s not found" % (name,)
class MachOTest(unittest.TestCase):
if sys.platform == "darwin":
Modified: packages/ctypes/trunk/ctypes/test/test_numbers.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_numbers.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_numbers.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_numbers.py Mon Jun 19 12:36:05 2006
@@ -34,14 +34,14 @@
else:
unsigned_types.append(c_ulonglong)
signed_types.append(c_longlong)
-
+
unsigned_ranges = valid_ranges(*unsigned_types)
signed_ranges = valid_ranges(*signed_types)
################################################################
class NumberTestCase(unittest.TestCase):
-
+
def test_default_init(self):
# default values are set to zero
for t in signed_types + unsigned_types + float_types:
@@ -132,7 +132,7 @@
# and alignment of an instance
self.failUnlessEqual((code, alignment(t())),
(code, align))
-
+
def test_int_from_address(self):
from array import array
for t in signed_types + unsigned_types:
@@ -152,7 +152,7 @@
# changing the value at the memory location changes v's value also
a[0] = 42
self.failUnlessEqual(v.value, a[0])
-
+
def test_float_from_address(self):
from array import array
@@ -168,7 +168,7 @@
def test_char_from_address(self):
from ctypes import c_char
from array import array
-
+
a = array('c', 'x')
v = c_char.from_address(a.buffer_info()[0])
self.failUnlessEqual(v.value, a[0])
@@ -185,7 +185,7 @@
## def test_perf(self):
## check_perf()
-
+
from ctypes import _SimpleCData
class c_int_S(_SimpleCData):
_type_ = "i"
@@ -227,7 +227,7 @@
# c_int(): 3.35 us
# c_int(999): 3.34 us
# c_int_S(): 3.23 us
-# c_int_S(999): 3.24 us
+# c_int_S(999): 3.24 us
# Python 2.2 -OO, win2k, P4 700 MHz:
#
Modified: packages/ctypes/trunk/ctypes/test/test_parameters.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_parameters.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_parameters.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_parameters.py Mon Jun 19 12:36:05 2006
@@ -18,7 +18,7 @@
pass
else:
set_conversion_mode(*self.prev_conv_mode)
-
+
def test_subclasses(self):
from ctypes import c_void_p, c_char_p
Modified: packages/ctypes/trunk/ctypes/test/test_pointers.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_pointers.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_pointers.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_pointers.py Mon Jun 19 12:36:05 2006
@@ -11,7 +11,7 @@
class PointersTestCase(unittest.TestCase):
def test_pointer_crash(self):
-
+
class A(POINTER(c_ulong)):
pass
@@ -20,7 +20,7 @@
self.failUnlessRaises(TypeError, A, c_ulong(33))
def test_pass_pointers(self):
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
func = dll._testfunc_p_p
func.restype = c_long
@@ -35,7 +35,7 @@
self.failUnlessEqual(res[0], 12345678)
def test_change_pointers(self):
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
func = dll._testfunc_p_p
i = c_int(87654)
@@ -70,7 +70,7 @@
return 0
callback = PROTOTYPE(func)
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
# This function expects a function pointer,
# and calls this with an integer pointer as parameter.
# The int pointer points to a table containing the numbers 1..10
@@ -84,7 +84,7 @@
## print self.result
doit(callback)
## print self.result
-
+
def test_basics(self):
from operator import delitem
for ct, pt in zip(ctype_types, python_types):
@@ -132,7 +132,7 @@
self.assertRaises(TypeError, len, p)
self.failUnlessEqual(p[0], 42)
self.failUnlessEqual(p.contents.value, 42)
-
+
def test_incomplete(self):
lpcell = POINTER("cell")
class cell(Structure):
@@ -156,7 +156,7 @@
def test_charpp( self ):
"""Test that a character pointer-to-pointer is correctly passed"""
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
func = dll._testfunc_c_p_p
func.restype = c_char_p
argv = (c_char_p * 2)()
@@ -166,6 +166,18 @@
result = func( byref(argc), argv )
assert result == 'world', result
-
+ def test_bug_1467852(self):
+ # http://sourceforge.net/tracker/?func=detail&atid=532154&aid=1467852&group_id=71702
+ x = c_int(5)
+ dummy = []
+ for i in range(32000):
+ dummy.append(c_int(i))
+ y = c_int(6)
+ p = pointer(x)
+ pp = pointer(p)
+ q = pointer(y)
+ pp[0] = q # <==
+ self.failUnlessEqual(p[0], 6)
+
if __name__ == '__main__':
unittest.main()
Modified: packages/ctypes/trunk/ctypes/test/test_prototypes.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_prototypes.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_prototypes.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_prototypes.py Mon Jun 19 12:36:05 2006
@@ -22,7 +22,20 @@
# In this case, there would have to be an additional reference to the argument...
import _ctypes_test
-testdll = cdll.load(_ctypes_test.__file__)
+testdll = CDLL(_ctypes_test.__file__)
+
+# Return machine address `a` as a (possibly long) non-negative integer.
+# Starting with Python 2.5, id(anything) is always non-negative, and
+# the ctypes addressof() inherits that via PyLong_FromVoidPtr().
+def positive_address(a):
+ if a >= 0:
+ return a
+ # View the bits in `a` as unsigned instead.
+ import struct
+ num_bits = struct.calcsize("P") * 8 # num bits in native machine address
+ a += 1L << num_bits
+ assert a >= 0
+ return a
def c_wbuffer(init):
n = len(init) + 1
@@ -43,8 +56,9 @@
ci = c_int(0)
func.argtypes = POINTER(c_int),
- self.failUnlessEqual(addressof(ci), func(byref(ci)))
-
+ self.failUnlessEqual(positive_address(addressof(ci)),
+ positive_address(func(byref(ci))))
+
func.argtypes = c_char_p,
self.assertRaises(ArgumentError, func, byref(ci))
@@ -73,7 +87,7 @@
func = testdll._testfunc_p_p
func.restype = c_char_p
func.argtypes = c_char_p,
-
+
self.failUnlessEqual(None, func(None))
self.failUnlessEqual("123", func("123"))
self.failUnlessEqual(None, func(c_char_p(None)))
Modified: packages/ctypes/trunk/ctypes/test/test_random_things.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_random_things.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_random_things.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_random_things.py Mon Jun 19 12:36:05 2006
@@ -51,16 +51,14 @@
def test_IntegerDivisionError(self):
cb = CFUNCTYPE(c_int, c_int)(callback_func)
out = self.capture_stderr(cb, 0)
- self.failUnlessEqual(out.splitlines()[-1],
- "ZeroDivisionError: "
- "integer division or modulo by zero")
+ self.failUnlessEqual(out.splitlines()[-1][:19],
+ "ZeroDivisionError: ")
def test_FloatDivisionError(self):
cb = CFUNCTYPE(c_int, c_double)(callback_func)
out = self.capture_stderr(cb, 0.0)
- self.failUnlessEqual(out.splitlines()[-1],
- "ZeroDivisionError: "
- "float division")
+ self.failUnlessEqual(out.splitlines()[-1][:19],
+ "ZeroDivisionError: ")
def test_TypeErrorDivisionError(self):
cb = CFUNCTYPE(c_int, c_char_p)(callback_func)
Modified: packages/ctypes/trunk/ctypes/test/test_refcounts.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_refcounts.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_refcounts.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_refcounts.py Mon Jun 19 12:36:05 2006
@@ -6,7 +6,7 @@
OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
import _ctypes_test
-dll = ctypes.cdll.load(_ctypes_test.__file__)
+dll = ctypes.CDLL(_ctypes_test.__file__)
class RefcountTestCase(unittest.TestCase):
@@ -48,7 +48,7 @@
# and may release it again
del f
self.failUnless(grc(func) >= 2)
-
+
# but now it must be gone
gc.collect()
self.failUnless(grc(func) == 2)
@@ -57,14 +57,14 @@
_fields_ = [("a", OtherCallback)]
x = X()
x.a = OtherCallback(func)
-
+
# the CFuncPtr instance holds atr least one refcount on func:
self.failUnless(grc(func) > 2)
# and may release it again
del x
self.failUnless(grc(func) >= 2)
-
+
# and now it must be gone again
gc.collect()
self.failUnlessEqual(grc(func), 2)
@@ -80,7 +80,7 @@
del f
gc.collect()
self.failUnlessEqual(grc(func), 2)
-
+
class AnotherLeak(unittest.TestCase):
def test_callback(self):
import sys
@@ -89,7 +89,7 @@
def func(a, b):
return a * b * 2
f = proto(func)
-
+
a = sys.getrefcount(ctypes.c_int)
f(1, 2)
self.failUnlessEqual(sys.getrefcount(ctypes.c_int), a)
Modified: packages/ctypes/trunk/ctypes/test/test_repr.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_repr.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_repr.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_repr.py Mon Jun 19 12:36:05 2006
@@ -1,23 +1,28 @@
from ctypes import *
import unittest
-nums = [c_byte, c_short, c_int, c_long, c_longlong,
+subclasses = []
+for base in [c_byte, c_short, c_int, c_long, c_longlong,
c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong,
- c_float, c_double]
+ c_float, c_double]:
+ class X(base):
+ pass
+ subclasses.append(X)
+
+class X(c_char):
+ pass
+
+# This test checks if the __repr__ is correct for subclasses of simple types
class ReprTest(unittest.TestCase):
def test_numbers(self):
- for typ in nums:
- self.failUnless(repr(typ(42)).startswith(typ.__name__))
- class X(typ):
- pass
- self.failUnlessEqual("<X object at", repr(X(42))[:12])
+ for typ in subclasses:
+ base = typ.__bases__[0]
+ self.failUnless(repr(base(42)).startswith(base.__name__))
+ self.failUnlessEqual("<X object at", repr(typ(42))[:12])
def test_char(self):
self.failUnlessEqual("c_char('x')", repr(c_char('x')))
-
- class X(c_char):
- pass
self.failUnlessEqual("<X object at", repr(X('x'))[:12])
if __name__ == "__main__":
Modified: packages/ctypes/trunk/ctypes/test/test_returnfuncptrs.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_returnfuncptrs.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_returnfuncptrs.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_returnfuncptrs.py Mon Jun 19 12:36:05 2006
@@ -8,7 +8,7 @@
def test_with_prototype(self):
# The _ctypes_test shared lib/dll exports quite some functions for testing.
# The get_strchr function returns a *pointer* to the C strchr function.
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
get_strchr = dll.get_strchr
get_strchr.restype = CFUNCTYPE(c_char_p, c_char_p, c_char)
strchr = get_strchr()
@@ -16,9 +16,9 @@
self.failUnlessEqual(strchr("abcdef", "x"), None)
self.assertRaises(ArgumentError, strchr, "abcdef", 3)
self.assertRaises(TypeError, strchr, "abcdef")
-
+
def test_without_prototype(self):
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
get_strchr = dll.get_strchr
# the default 'c_int' would not work on systems where sizeof(int) != sizeof(void *)
get_strchr.restype = c_void_p
Modified: packages/ctypes/trunk/ctypes/test/test_slicing.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_slicing.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_slicing.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_slicing.py Mon Jun 19 12:36:05 2006
@@ -37,7 +37,7 @@
def test_char_ptr(self):
s = "abcdefghijklmnopqrstuvwxyz\0"
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
dll.my_strdup.restype = POINTER(c_char)
res = dll.my_strdup(s)
self.failUnlessEqual(res[:len(s)], s)
@@ -65,7 +65,7 @@
def test_wchar_ptr(self):
s = u"abcdefghijklmnopqrstuvwxyz\0"
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
dll.my_wcsdup.restype = POINTER(c_wchar)
dll.my_wcsdup.argtypes = POINTER(c_wchar),
res = dll.my_wcsdup(s)
Modified: packages/ctypes/trunk/ctypes/test/test_stringptr.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_stringptr.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_stringptr.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_stringptr.py Mon Jun 19 12:36:05 2006
@@ -3,7 +3,7 @@
import _ctypes_test
-lib = cdll.load(_ctypes_test.__file__)
+lib = CDLL(_ctypes_test.__file__)
class StringPtrTestCase(unittest.TestCase):
Modified: packages/ctypes/trunk/ctypes/test/test_strings.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_strings.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_strings.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_strings.py Mon Jun 19 12:36:05 2006
@@ -46,7 +46,7 @@
BUF = c_char * 4
buf = BUF()
## print c_char_p.from_param(buf)
-
+
def test_param_2(self):
BUF = c_char * 4
buf = BUF()
@@ -103,9 +103,9 @@
def XX_test_sized_strings(self):
- # New in releases later than 0.4.0:
+ # New in releases later than 0.4.0:
self.assertRaises(TypeError, c_string, None)
-
+
# New in releases later than 0.4.0:
# c_string(number) returns an empty string of size number
self.failUnless(len(c_string(32).raw) == 32)
@@ -181,7 +181,7 @@
# One char too long values:
self.assertRaises(ValueError, setattr, cs, "value", u"1234567")
-
+
def run_test(rep, msg, func, arg):
items = range(rep)
from time import clock
Modified: packages/ctypes/trunk/ctypes/test/test_structures.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_structures.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_structures.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_structures.py Mon Jun 19 12:36:05 2006
@@ -56,7 +56,7 @@
"f": c_float,
"d": c_double,
}
-
+
def test_simple_structs(self):
for code, tp in self.formats.items():
class X(Structure):
@@ -90,7 +90,7 @@
("b", Y)]
self.failUnlessEqual(alignment(SI), max(alignment(Y), alignment(X)))
self.failUnlessEqual(sizeof(SI), calcsize("3s0i 3si 0i"))
-
+
class IS(Structure):
_fields_ = [("b", Y),
("a", X)]
@@ -215,7 +215,7 @@
# too long
self.assertRaises(ValueError, Person, "1234567", 5)
-
+
def test_keyword_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
@@ -291,13 +291,23 @@
cls, msg = self.get_except(Person, "Someone", (1, 2))
self.failUnlessEqual(cls, RuntimeError)
- self.failUnlessEqual(msg,
- "(Phone) exceptions.TypeError: "
- "expected string or Unicode object, int found")
+ # In Python 2.5, Exception is a new-style class, and the repr changed
+ if issubclass(Exception, object):
+ self.failUnlessEqual(msg,
+ "(Phone) <class 'exceptions.TypeError'>: "
+ "expected string or Unicode object, int found")
+ else:
+ self.failUnlessEqual(msg,
+ "(Phone) exceptions.TypeError: "
+ "expected string or Unicode object, int found")
cls, msg = self.get_except(Person, "Someone", ("a", "b", "c"))
self.failUnlessEqual(cls, RuntimeError)
- self.failUnlessEqual(msg, "(Phone) exceptions.ValueError: too many initializers")
+ if issubclass(Exception, object):
+ self.failUnlessEqual(msg,
+ "(Phone) <class 'exceptions.ValueError'>: too many initializers")
+ else:
+ self.failUnlessEqual(msg, "(Phone) exceptions.ValueError: too many initializers")
def get_except(self, func, *args):
@@ -305,7 +315,7 @@
func(*args)
except Exception, detail:
return detail.__class__, str(detail)
-
+
## def test_subclass_creation(self):
## meta = type(Structure)
@@ -363,4 +373,3 @@
if __name__ == '__main__':
unittest.main()
-
Modified: packages/ctypes/trunk/ctypes/test/test_unicode.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_unicode.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_unicode.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_unicode.py Mon Jun 19 12:36:05 2006
@@ -8,7 +8,7 @@
pass
else:
import _ctypes_test
- dll = ctypes.cdll.load(_ctypes_test.__file__)
+ dll = ctypes.CDLL(_ctypes_test.__file__)
wcslen = dll.my_wcslen
wcslen.argtypes = [ctypes.c_wchar_p]
@@ -66,7 +66,7 @@
self.failUnlessEqual(buf[:], u"ab\0\0\0\0")
import _ctypes_test
- func = ctypes.cdll.load(_ctypes_test.__file__)._testfunc_p_p
+ func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p
class StringTestCase(UnicodeTestCase):
def setUp(self):
Modified: packages/ctypes/trunk/ctypes/test/test_values.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_values.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_values.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_values.py Mon Jun 19 12:36:05 2006
@@ -10,7 +10,7 @@
class ValuesTestCase(unittest.TestCase):
def test_an_integer(self):
- ctdll = cdll.load(_ctypes_test.__file__)
+ ctdll = CDLL(_ctypes_test.__file__)
an_integer = c_int.in_dll(ctdll, "an_integer")
x = an_integer.value
self.failUnlessEqual(x, ctdll.get_an_integer())
@@ -18,7 +18,7 @@
self.failUnlessEqual(x*2, ctdll.get_an_integer())
def test_undefined(self):
- ctdll = cdll.load(_ctypes_test.__file__)
+ ctdll = CDLL(_ctypes_test.__file__)
self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")
class Win_ValuesTestCase(unittest.TestCase):
Modified: packages/ctypes/trunk/ctypes/test/test_win32.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/test/test_win32.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/test/test_win32.py (original)
+++ packages/ctypes/trunk/ctypes/test/test_win32.py Mon Jun 19 12:36:05 2006
@@ -43,22 +43,22 @@
class Structures(unittest.TestCase):
- def test_struct_by_value(self):
- class POINT(Structure):
- _fields_ = [("x", c_long),
- ("y", c_long)]
+ def test_struct_by_value(self):
+ class POINT(Structure):
+ _fields_ = [("x", c_long),
+ ("y", c_long)]
- class RECT(Structure):
- _fields_ = [("left", c_long),
- ("top", c_long),
- ("right", c_long),
- ("bottom", c_long)]
+ class RECT(Structure):
+ _fields_ = [("left", c_long),
+ ("top", c_long),
+ ("right", c_long),
+ ("bottom", c_long)]
- dll = cdll.load(_ctypes_test.__file__)
+ dll = CDLL(_ctypes_test.__file__)
- pt = POINT(10, 10)
- rect = RECT(0, 0, 20, 20)
- self.failUnlessEqual(1, dll.PointInRect(byref(rect), pt))
+ pt = POINT(10, 10)
+ rect = RECT(0, 0, 20, 20)
+ self.failUnlessEqual(1, dll.PointInRect(byref(rect), pt))
if __name__ == '__main__':
unittest.main()
Modified: packages/ctypes/trunk/ctypes/util.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/ctypes/util.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/ctypes/util.py (original)
+++ packages/ctypes/trunk/ctypes/util.py Mon Jun 19 12:36:05 2006
@@ -1,1 +1,122 @@
-# ctypes.util is no longer used.
+import sys, os
+import ctypes
+
+# find_library(name) returns the pathname of a library, or None.
+if os.name == "nt":
+ def find_library(name):
+ # See MSDN for the REAL search order.
+ for directory in os.environ['PATH'].split(os.pathsep):
+ fname = os.path.join(directory, name)
+ if os.path.exists(fname):
+ return fname
+ if fname.lower().endswith(".dll"):
+ continue
+ fname = fname + ".dll"
+ if os.path.exists(fname):
+ return fname
+ return None
+
+if os.name == "ce":
+ # search path according to MSDN:
+ # - absolute path specified by filename
+ # - The .exe launch directory
+ # - the Windows directory
+ # - ROM dll files (where are they?)
+ # - OEM specified search path: HKLM\Loader\SystemPath
+ def find_library(name):
+ return name
+
+if os.name == "posix" and sys.platform == "darwin":
+ from ctypes.macholib.dyld import dyld_find as _dyld_find
+ def find_library(name):
+ possible = ['lib%s.dylib' % name,
+ '%s.dylib' % name,
+ '%s.framework/%s' % (name, name)]
+ for name in possible:
+ try:
+ return _dyld_find(name)
+ except ValueError:
+ continue
+ return None
+
+elif os.name == "posix":
+ # Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump
+ import re, tempfile
+
+ def _findLib_gcc(name):
+ expr = '[^\(\)\s]*lib%s\.[^\(\)\s]*' % name
+ cmd = 'if type gcc &>/dev/null; then CC=gcc; else CC=cc; fi;' \
+ '$CC -Wl,-t -o /dev/null 2>&1 -l' + name
+ try:
+ fdout, outfile = tempfile.mkstemp()
+ fd = os.popen(cmd)
+ trace = fd.read()
+ err = fd.close()
+ finally:
+ try:
+ os.unlink(outfile)
+ except OSError, e:
+ if e.errno != errno.ENOENT:
+ raise
+ res = re.search(expr, trace)
+ if not res:
+ return None
+ return res.group(0)
+
+ def _findLib_ld(name):
+ expr = '/[^\(\)\s]*lib%s\.[^\(\)\s]*' % name
+ res = re.search(expr, os.popen('/sbin/ldconfig -p 2>/dev/null').read())
+ if not res:
+ # Hm, this works only for libs needed by the python executable.
+ cmd = 'ldd %s 2>/dev/null' % sys.executable
+ res = re.search(expr, os.popen(cmd).read())
+ if not res:
+ return None
+ return res.group(0)
+
+ def _get_soname(f):
+ cmd = "objdump -p -j .dynamic 2>/dev/null " + f
+ res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read())
+ if not res:
+ return None
+ return res.group(1)
+
+ def find_library(name):
+ lib = _findLib_ld(name) or _findLib_gcc(name)
+ if not lib:
+ return None
+ return _get_soname(lib)
+
+################################################################
+# test code
+
+def test():
+ from ctypes import cdll
+ if os.name == "nt":
+ print cdll.msvcrt
+ print cdll.load("msvcrt")
+ print find_library("msvcrt")
+
+ if os.name == "posix":
+ # find and load_version
+ print find_library("m")
+ print find_library("c")
+ print find_library("bz2")
+
+ # getattr
+## print cdll.m
+## print cdll.bz2
+
+ # load
+ if sys.platform == "darwin":
+ print cdll.LoadLibrary("libm.dylib")
+ print cdll.LoadLibrary("libcrypto.dylib")
+ print cdll.LoadLibrary("libSystem.dylib")
+ print cdll.LoadLibrary("System.framework/System")
+ else:
+ print cdll.LoadLibrary("libm.so")
+ print cdll.LoadLibrary("libcrypt.so")
+ print find_library("crypt")
+
+if __name__ == "__main__":
+ test()
Modified: packages/ctypes/trunk/setup.py
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/setup.py?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/setup.py (original)
+++ packages/ctypes/trunk/setup.py Mon Jun 19 12:36:05 2006
@@ -1,6 +1,6 @@
#!/usr/bin/env python
#
-# $Id: setup.py,v 1.122.2.15 2006/02/14 19:02:39 theller Exp $
+# $Id: setup.py,v 1.140 2006/04/14 15:49:33 theller Exp $
#
#
@@ -11,7 +11,7 @@
LIBFFI_SOURCES='source/libffi'
-__version__ = "0.9.9.3"
+__version__ = "0.9.9.6"
################################################################
@@ -30,6 +30,7 @@
from distutils.command import install_data
from distutils.dir_util import mkpath
from distutils.util import get_platform
+from distutils.cygwinccompiler import Mingw32CCompiler
################################################################
# Manipulate the environment for the build process.
@@ -60,10 +61,7 @@
self.build_base = 'build'
self.use_resources = ""
self.refcounts = False
- if sys.platform == "win32":
- self.tests = "ctypes.test,comtypes.test"
- else:
- self.tests = "ctypes.test"
+ self.tests = "ctypes.test"
# initialize_options()
@@ -82,8 +80,8 @@
ctypes.test.use_resources.extend(self.use_resources)
for name in self.tests:
- package = __import__(name, globals(), locals(), ['*'])
- print "Testing package", name
+ package = __import__(name, globals(), locals(), ['*'])
+ print "Testing package", name, (sys.version, sys.platform, os.name)
ctypes.test.run_tests(package,
"test_*.py",
self.verbose,
@@ -128,6 +126,20 @@
# Add .S (preprocessed assembly) to C compiler source extensions.
self.compiler.src_extensions.append('.S')
+ if sys.platform == "win32":
+ if isinstance(self.compiler, Mingw32CCompiler):
+ # Windows lowercases the extensions, it seems, before
+ # determining how to compile a file. So, even if win32.S
+ # is in sources, we have to add '.s'.
+ self.compiler.src_extensions.append('.s')
+ for ext in self.extensions:
+ if ext.name == "_ctypes":
+ ext.sources.remove("source/libffi_msvc/win32.c")
+ else:
+ for ext in self.extensions:
+ if ext.name == "_ctypes":
+ ext.sources.remove("source/libffi_msvc/win32.S")
+ ext.extra_link_args = []
build_ext.build_ext.build_extensions(self)
@@ -197,15 +209,15 @@
clean.clean.run(self)
class my_install_data(install_data.install_data):
- """A custom install_data command, which will install it's files
- into the standard directories (normally lib/site-packages).
- """
- def finalize_options(self):
- if self.install_dir is None:
- installobj = self.distribution.get_command_obj('install')
- self.install_dir = installobj.install_lib
- print 'Installing data files to %s' % self.install_dir
- install_data.install_data.finalize_options(self)
+ """A custom install_data command, which will install it's files
+ into the standard directories (normally lib/site-packages).
+ """
+ def finalize_options(self):
+ if self.install_dir is None:
+ installobj = self.distribution.get_command_obj('install')
+ self.install_dir = installobj.install_lib
+ print 'Installing data files to %s' % self.install_dir
+ install_data.install_data.finalize_options(self)
################################################################
# Specify the _ctypes extension
@@ -227,15 +239,48 @@
# types.c is no longer needed, ffi_type defs are in cfield.c
"source/libffi_msvc/ffi.c",
"source/libffi_msvc/prep_cif.c",
+ # One of these will be removed, in my_build_ext, depending
+ # on the compiler used:
"source/libffi_msvc/win32.c",
+ "source/libffi_msvc/win32.S",
])
+ if sys.version_info >= (2, 4):
+ extra_compile_args = []
+ # enable 64-bit portability warnings
+## extra_compile_args = ["/Wp64"]
+ else:
+ extra_compile_args = []
+
+ # Extra arguments passed to linker from MinGW,
+ # will be removed, in my_build_ext, if compiler <> MinGW
+ extra_link_args = []
+
+ # In MinGW32, the first linker option should be:
+ # -Xlinker --enable-stdcall-fixup
+ # but here this option is split into two options to
+ # force distutils not to surroud the entire option
+ # with double quotes as it sees a space in it. So:
+
+ extra_link_args.extend(["-Xlinker", "--enable-stdcall-fixup",
+
+ # In MinGW32, the --kill-at linker option forces MinGW to
+ # remove the @XY decoration from function names, hence making
+ # the stdcall functions of _ctypes_test and those tested in
+ # test_cfuns.py behave similarly to the one compiled in MSVC.
+
+ "-Wl,--kill-at"])
+
extensions = [Extension("_ctypes",
+ extra_compile_args = extra_compile_args,
+ extra_link_args = extra_link_args,
export_symbols=["DllGetClassObject,PRIVATE",
"DllCanUnloadNow,PRIVATE"],
- libraries=["ole32", "user32", "oleaut32"],
+ libraries=["ole32", "user32", "oleaut32", "uuid"],
include_dirs=["source/libffi_msvc"],
**kw),
Extension("_ctypes_test",
+ extra_compile_args = extra_compile_args,
+ extra_link_args = extra_link_args,
libraries=["oleaut32", "user32"],
sources=["source/_ctypes_test.c"],
include_dirs=["source/libffi_msvc"],
@@ -268,24 +313,9 @@
################################################################
# the ctypes package
#
-packages = ["ctypes", "ctypes.wrap", "ctypes.macholib", "ctypes.test"]
-package_dir = {}
-
-################################################################
-# options for distutils
-#
-setup_options = {}
-
-if sys.platform == 'win32':
- # Use different MANIFEST templates, to minimize the distribution
- # size. Also, the MANIFEST templates behave differently on
- # Windows and Linux (distutils bug?).
- # Finally, force rebuilding the MANIFEST file
-
- setup_options["sdist"] = {"template": "MANIFEST.windows.in", "force_manifest": 1}
-else:
- setup_options["sdist"] = {"template": "MANIFEST.other.in", "force_manifest": 1}
-data_files = []
+packages = ["ctypes",
+ "ctypes.macholib",
+ "ctypes.test"]
################################################################
# pypi classifiers
@@ -306,14 +336,14 @@
################################################################
# main section
#
+##from ce import ce_install_lib
+
if __name__ == '__main__':
setup(name="ctypes",
## entry_points = {"console_scripts" : ["xml2py = ctypes.wrap.xml2py:main",
## "h2xml = ctypes.wrap.h2xml:main"]},
ext_modules = extensions,
- package_dir = package_dir,
packages = packages,
- data_files = data_files,
classifiers = classifiers,
@@ -325,10 +355,12 @@
license="MIT License",
url="http://starship.python.net/crew/theller/ctypes.html",
platforms=["windows", "Linux", "MacOS X", "Solaris", "FreeBSD"],
-
+
cmdclass = {'test': test, 'build_py': my_build_py, 'build_ext': my_build_ext,
- 'clean': my_clean, 'install_data': my_install_data},
- options = setup_options
+ 'clean': my_clean, 'install_data': my_install_data,
+## 'ce_install_lib': ce_install_lib
+ },
+
)
## Local Variables:
Modified: packages/ctypes/trunk/source/_ctypes.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/_ctypes.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/_ctypes.c (original)
+++ packages/ctypes/trunk/source/_ctypes.c Mon Jun 19 12:36:05 2006
@@ -105,6 +105,10 @@
#include <ffi.h>
#ifdef MS_WIN32
#include <windows.h>
+#include <malloc.h>
+#ifndef IS_INTRESOURCE
+#define IS_INTRESOURCE(x) (((size_t)(x) >> 16) == 0)
+#endif
# ifdef _WIN32_WCE
/* Unlike desktop Windows, WinCE has both W and A variants of
GetProcAddress, but the default W version is not what we want */
@@ -112,7 +116,7 @@
# define GetProcAddress GetProcAddressA
# endif
#else
-#include <dlfcn.h>
+#include "ctypes_dlfcn.h"
#endif
#include "ctypes.h"
@@ -257,7 +261,7 @@
return NULL;
}
#else
- address = (void *)dlsym(handle, name);
+ address = (void *)ctypes_dlsym(handle, name);
if (!address) {
PyErr_Format(PyExc_ValueError,
#ifdef __CYGWIN__
@@ -265,7 +269,7 @@
"symbol '%s' not found (%s) ",
name,
#endif
- dlerror());
+ ctypes_dlerror());
return NULL;
}
#endif
@@ -285,6 +289,7 @@
if (PyCArg_CheckExact(value)) {
PyCArgObject *p = (PyCArgObject *)value;
PyObject *ob = p->obj;
+ const char *ob_name;
StgDictObject *dict;
dict = PyType_stgdict(type);
@@ -296,10 +301,10 @@
Py_INCREF(value);
return value;
}
+ ob_name = (ob) ? ob->ob_type->tp_name : "???";
PyErr_Format(PyExc_TypeError,
"expected %s instance instead of pointer to %s",
- ((PyTypeObject *)type)->tp_name,
- ob->ob_type->tp_name);
+ ((PyTypeObject *)type)->tp_name, ob_name);
return NULL;
}
#if 1
@@ -335,7 +340,7 @@
};
static PyObject *
-CDataType_repeat(PyObject *self, int length)
+CDataType_repeat(PyObject *self, Py_ssize_t length)
{
return CreateArrayType(self, length);
}
@@ -506,12 +511,12 @@
static int
PointerType_SetProto(StgDictObject *stgdict, PyObject *proto)
{
- if (proto && !PyType_Check(proto)) {
+ if (!proto || !PyType_Check(proto)) {
PyErr_SetString(PyExc_TypeError,
"_type_ must be a type");
return -1;
}
- if (proto && !PyType_stgdict(proto)) {
+ if (!PyType_stgdict(proto)) {
PyErr_SetString(PyExc_TypeError,
"_type_ must have storage info");
return -1;
@@ -543,8 +548,8 @@
return NULL;
stgdict->size = sizeof(void *);
stgdict->align = getentry("P")->pffi_type->alignment;
- stgdict->length = 2;
- stgdict->ffi_type = ffi_type_pointer;
+ stgdict->length = 1;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
if (proto && -1 == PointerType_SetProto(stgdict, proto)) {
@@ -695,7 +700,7 @@
CharArray_set_raw(CDataObject *self, PyObject *value)
{
char *ptr;
- int size;
+ Py_ssize_t size;
if (PyBuffer_Check(value)) {
size = value->ob_type->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
if (size < 0)
@@ -899,7 +904,7 @@
PyObject *typedict;
int length;
- int itemsize, itemalign, itemlen;
+ int itemsize, itemalign;
typedict = PyTuple_GetItem(args, 2);
if (!typedict)
@@ -936,7 +941,6 @@
itemsize = itemdict->size;
itemalign = itemdict->align;
- itemlen = itemdict->length;
stgdict->size = itemsize * length;
stgdict->align = itemalign;
@@ -945,7 +949,7 @@
stgdict->proto = proto;
/* Arrays are passed as pointers to function calls. */
- stgdict->ffi_type = ffi_type_pointer;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
/* create the new instance (which is a class,
since we are a metatype!) */
@@ -1219,6 +1223,19 @@
return value;
}
}
+/* function pointer */
+ if (CFuncPtrObject_Check(value)) {
+ PyCArgObject *parg;
+ CFuncPtrObject *func;
+ func = (CFuncPtrObject *)value;
+ parg = new_CArgObject();
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'P';
+ Py_INCREF(value);
+ parg->value.p = *(void **)func->b_ptr;
+ parg->obj = value;
+ return (PyObject *)parg;
+ }
/* c_char_p, c_wchar_p */
stgd = PyObject_stgdict(value);
if (stgd && CDataObject_Check(value) && stgd->proto && PyString_Check(stgd->proto)) {
@@ -1264,9 +1281,13 @@
PyTypeObject *result;
StgDictObject *stgdict;
PyObject *name = PyTuple_GET_ITEM(args, 0);
- PyObject *swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
+ PyObject *swapped_args;
static PyObject *suffix;
- int i;
+ Py_ssize_t i;
+
+ swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
+ if (!swapped_args)
+ return NULL;
if (suffix == NULL)
#ifdef WORDS_BIGENDIAN
@@ -1275,8 +1296,10 @@
suffix = PyString_FromString("_be");
#endif
- Py_INCREF(suffix);
- PyString_ConcatAndDel(&name, suffix);
+ Py_INCREF(name);
+ PyString_Concat(&name, suffix);
+ if (name == NULL)
+ return NULL;
PyTuple_SET_ITEM(swapped_args, 0, name);
for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
@@ -1297,7 +1320,7 @@
if (!stgdict) /* XXX leaks result! */
return NULL;
- stgdict->ffi_type = *fmt->pffi_type;
+ stgdict->ffi_type_pointer = *fmt->pffi_type;
stgdict->align = fmt->pffi_type->alignment;
stgdict->length = 0;
stgdict->size = fmt->pffi_type->size;
@@ -1355,7 +1378,7 @@
fmt = getentry(PyString_AS_STRING(proto));
- stgdict->ffi_type = *fmt->pffi_type;
+ stgdict->ffi_type_pointer = *fmt->pffi_type;
stgdict->align = fmt->pffi_type->alignment;
stgdict->length = 0;
stgdict->size = fmt->pffi_type->size;
@@ -1450,6 +1473,7 @@
PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result);
PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
#endif
+ Py_DECREF(swapped);
};
return (PyObject *)result;
@@ -1624,7 +1648,7 @@
stgdict->size = sizeof(void *);
stgdict->setfunc = NULL;
stgdict->getfunc = NULL;
- stgdict->ffi_type = ffi_type_pointer;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_");
if (!ob || !PyInt_Check(ob)) {
@@ -1789,13 +1813,11 @@
{
char string[256]; /* XXX is that enough? */
char *cp = string;
- int len;
*cp++ = index + '0';
while (target->b_base) {
*cp++ = target->b_index + '0';
target = target->b_base;
}
- len = cp - string;
return PyString_FromStringAndSize(string, cp-string);
}
/* Keep a reference to 'keep' in the 'target', at index 'index' */
@@ -1806,7 +1828,7 @@
* key int the root object's _objects dict.
*/
static int
-KeepRef(CDataObject *target, int index, PyObject *keep)
+KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
{
int result;
CDataObject *ob;
@@ -1845,8 +1867,10 @@
static int
CData_clear(CDataObject *self)
{
+ StgDictObject *dict = PyObject_stgdict((PyObject *)self);
Py_CLEAR(self->b_objects);
- if (self->b_needsfree)
+ if ((self->b_needsfree)
+ && ((size_t)dict->size > sizeof(self->b_value)))
PyMem_Free(self->b_ptr);
self->b_ptr = NULL;
Py_CLEAR(self->b_base);
@@ -1873,8 +1897,9 @@
{ NULL },
};
-static int CData_GetBuffer(CDataObject *self, int seg, void **pptr)
-{
+static Py_ssize_t CData_GetBuffer(PyObject *_self, Py_ssize_t seg, void **pptr)
+{
+ CDataObject *self = (CDataObject *)_self;
if (seg != 0) {
/* Hm. Must this set an exception? */
return -1;
@@ -1883,7 +1908,7 @@
return self->b_size;
}
-static int CData_GetSegcount(CDataObject *self, int *lenp)
+static Py_ssize_t CData_GetSegcount(PyObject *_self, Py_ssize_t *lenp)
{
if (lenp)
*lenp = 1;
@@ -1891,10 +1916,10 @@
}
static PyBufferProcs CData_as_buffer = {
- (getreadbufferproc)CData_GetBuffer,
- (getwritebufferproc)CData_GetBuffer,
- (getsegcountproc)CData_GetSegcount,
- (getcharbufferproc)NULL,
+ CData_GetBuffer,
+ CData_GetBuffer,
+ CData_GetSegcount,
+ NULL,
};
/*
@@ -1967,15 +1992,15 @@
static void CData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
{
- if (dict->size <= sizeof(obj->b_value)) {
+ if ((size_t)dict->size <= sizeof(obj->b_value)) {
/* No need to call malloc, can use the default buffer */
obj->b_ptr = (char *)&obj->b_value;
- obj->b_needsfree = 0;
+ obj->b_needsfree = 1;
} else {
/* In python 2.4, and ctypes 0.9.6, the malloc call took about
33% of the creation time for c_int().
*/
- obj->b_ptr = PyMem_Malloc(dict->size);
+ obj->b_ptr = (char *)PyMem_Malloc(dict->size);
obj->b_needsfree = 1;
memset(obj->b_ptr, 0, dict->size);
}
@@ -1983,7 +2008,7 @@
}
PyObject *
-CData_FromBaseObj(PyObject *type, PyObject *base, int index, char *adr)
+CData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
{
CDataObject *cmem;
StgDictObject *dict;
@@ -2040,7 +2065,7 @@
if (!pd)
return NULL;
assert(CDataObject_Check(pd));
- pd->b_ptr = buf;
+ pd->b_ptr = (char *)buf;
pd->b_length = dict->length;
pd->b_size = dict->size;
return (PyObject *)pd;
@@ -2062,7 +2087,7 @@
PyObject *
CData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
- int index, int size, char *adr)
+ Py_ssize_t index, Py_ssize_t size, char *adr)
{
StgDictObject *dict;
if (getfunc)
@@ -2079,7 +2104,7 @@
*/
static PyObject *
_CData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
- int size, char *ptr)
+ Py_ssize_t size, char *ptr)
{
CDataObject *src;
@@ -2175,7 +2200,7 @@
*/
int
CData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
- int index, int size, char *ptr)
+ Py_ssize_t index, Py_ssize_t size, char *ptr)
{
CDataObject *mem = (CDataObject *)dst;
PyObject *result;
@@ -2383,6 +2408,11 @@
address = (PPROC)GetProcAddress(handle, name);
if (address)
return address;
+
+ if (((size_t)name & ~0xFFFF) == 0) {
+ return NULL;
+ }
+
/* It should not happen that dict is NULL, but better be safe */
if (dict==NULL || dict->flags & FUNCFLAG_CDECL)
return address;
@@ -2391,7 +2421,7 @@
funcname -> _funcname@<n>
where n is 0, 4, 8, 12, ..., 128
*/
- mangled_name = _alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
+ mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
for (i = 0; i < 32; ++i) {
sprintf(mangled_name, "_%s@%d", name, i*4);
address = (PPROC)GetProcAddress(handle, mangled_name);
@@ -2488,6 +2518,28 @@
return 1;
}
+static int
+_get_name(PyObject *obj, char **pname)
+{
+#ifdef MS_WIN32
+ if (PyInt_Check(obj) || PyLong_Check(obj)) {
+ /* We have to use MAKEINTRESOURCEA for Windows CE.
+ Works on Windows as well, of course.
+ */
+ *pname = MAKEINTRESOURCEA(PyInt_AsUnsignedLongMask(obj) & 0xFFFF);
+ return 1;
+ }
+#endif
+ if (PyString_Check(obj) || PyUnicode_Check(obj)) {
+ *pname = PyString_AsString(obj);
+ return *pname ? 1 : 0;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "function name must be string or integer");
+ return 0;
+}
+
+
static PyObject *
CFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
@@ -2499,7 +2551,7 @@
void *handle;
PyObject *paramflags = NULL;
- if (!PyArg_ParseTuple(args, "sO|O", &name, &dll, ¶mflags))
+ if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags))
return NULL;
if (paramflags == Py_None)
paramflags = NULL;
@@ -2524,13 +2576,18 @@
#ifdef MS_WIN32
address = FindAddress(handle, name, (PyObject *)type);
if (!address) {
- PyErr_Format(PyExc_AttributeError,
- "function '%s' not found",
- name);
+ if (!IS_INTRESOURCE(name))
+ PyErr_Format(PyExc_AttributeError,
+ "function '%s' not found",
+ name);
+ else
+ PyErr_Format(PyExc_AttributeError,
+ "function ordinal %d not found",
+ (WORD)(size_t)name);
return NULL;
}
#else
- address = (PPROC)dlsym(handle, name);
+ address = (PPROC)ctypes_dlsym(handle, name);
if (!address) {
PyErr_Format(PyExc_AttributeError,
#ifdef __CYGWIN__
@@ -2538,7 +2595,7 @@
"function '%s' not found (%s) ",
name,
#endif
- dlerror());
+ ctypes_dlerror());
return NULL;
}
#endif
@@ -2603,8 +2660,9 @@
"O" - must be a callable, creates a C callable function
two or more argument forms (the third argument is a paramflags tuple)
- "sO|O" - function name, dll object (with an integer handle)
- "is|O" - vtable index, method name, creates callable calling COM vtbl
+ "(sO)|..." - (function name, dll object (with an integer handle)), paramflags
+ "(iO)|..." - (function ordinal, dll object (with an integer handle)), paramflags
+ "is|..." - vtable index, method name, creates callable calling COM vtbl
*/
static PyObject *
CFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@@ -2612,19 +2670,18 @@
CFuncPtrObject *self;
PyObject *callable;
StgDictObject *dict;
- THUNK thunk;
+ ffi_info *thunk;
if (PyTuple_GET_SIZE(args) == 0)
return GenericCData_new(type, args, kwds);
- /* Shouldn't the following better be done in __init__? */
- if (2 <= PyTuple_GET_SIZE(args)) {
+ if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
+ return CFuncPtr_FromDll(type, args, kwds);
+
#ifdef MS_WIN32
- if (PyInt_Check(PyTuple_GET_ITEM(args, 0)))
- return CFuncPtr_FromVtblIndex(type, args, kwds);
+ if (2 <= PyTuple_GET_SIZE(args) && PyInt_Check(PyTuple_GET_ITEM(args, 0)))
+ return CFuncPtr_FromVtblIndex(type, args, kwds);
#endif
- return CFuncPtr_FromDll(type, args, kwds);
- }
if (1 == PyTuple_GET_SIZE(args)
&& (PyInt_Check(PyTuple_GET_ITEM(args, 0))
@@ -2781,7 +2838,7 @@
static PyObject *
_build_callargs(CFuncPtrObject *self, PyObject *argtypes,
PyObject *inargs, PyObject *kwds,
- int *poutmask, int *pinoutmask, int *pnumretvals)
+ int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
{
PyObject *paramflags = self->paramflags;
PyObject *callargs;
@@ -2835,8 +2892,14 @@
switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
case PARAMFLAG_FIN | PARAMFLAG_FLCID:
- /* ['in', 'lcid'] parameter. Always taken from defval */
- Py_INCREF(defval);
+ /* ['in', 'lcid'] parameter. Always taken from defval,
+ if given, else the integer 0. */
+ if (defval == NULL) {
+ defval = PyInt_FromLong(0);
+ if (defval == NULL)
+ goto error;
+ } else
+ Py_INCREF(defval);
PyTuple_SET_ITEM(callargs, i, defval);
break;
case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
@@ -2939,9 +3002,10 @@
*/
static PyObject *
_build_result(PyObject *result, PyObject *callargs,
- int outmask, int inoutmask, int numretvals)
-{
- int i, index, bit;
+ int outmask, int inoutmask, unsigned int numretvals)
+{
+ unsigned int i, index;
+ int bit;
PyObject *tup = NULL;
if (callargs == NULL)
@@ -2952,6 +3016,7 @@
}
Py_DECREF(result);
+ /* tup will not be allocated if numretvals == 1 */
/* allocate tuple to hold the result */
if (numretvals > 1) {
tup = PyTuple_New(numretvals);
@@ -3009,7 +3074,7 @@
int inoutmask;
int outmask;
- int numretvals;
+ unsigned int numretvals;
assert(dict); /* if not, it's a bug */
restype = self->restype ? self->restype : dict->restype;
@@ -3145,13 +3210,11 @@
Py_CLEAR(self->converters);
Py_CLEAR(self->paramflags);
- if (self->b_needsfree)
- PyMem_Free(self->b_ptr);
- self->b_ptr = NULL;
-
- if (self->thunk)
- FreeCallback(self->thunk);
- self->thunk = NULL;
+ if (self->thunk) {
+ FreeClosure(self->thunk->pcl);
+ PyMem_Free(self->thunk);
+ self->thunk = NULL;
+ }
return CData_clear((CDataObject *)self);
}
@@ -3245,7 +3308,7 @@
parg->tag = 'V';
stgdict = PyObject_stgdict((PyObject *)self);
- parg->pffi_type = &stgdict->ffi_type;
+ parg->pffi_type = &stgdict->ffi_type_pointer;
/* For structure parameters (by value), parg->value doesn't contain the structure
data itself, instead parg->value.p *points* to the structure's data
See also _ctypes.c, function _call_function_pointer().
@@ -3279,6 +3342,8 @@
if (!fields) {
PyErr_Clear();
fields = PyTuple_New(0);
+ if (!fields)
+ return -1;
}
if (PyTuple_GET_SIZE(args) > PySequence_Length(fields)) {
@@ -3320,7 +3385,7 @@
if (kwds) {
PyObject *key, *value;
- int pos = 0;
+ Py_ssize_t pos = 0;
while(PyDict_Next(kwds, &pos, &key, &value)) {
if (-1 == PyObject_SetAttr(self, key, value))
return -1;
@@ -3449,8 +3514,9 @@
}
static PyObject *
-Array_item(CDataObject *self, int index)
-{
+Array_item(PyObject *_self, Py_ssize_t index)
+{
+ CDataObject *self = (CDataObject *)_self;
int offset, size;
StgDictObject *stgdict;
@@ -3473,12 +3539,13 @@
}
static PyObject *
-Array_slice(CDataObject *self, int ilow, int ihigh)
-{
+Array_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
+{
+ CDataObject *self = (CDataObject *)_self;
StgDictObject *stgdict, *itemdict;
PyObject *proto;
PyListObject *np;
- int i, len;
+ Py_ssize_t i, len;
if (ilow < 0)
ilow = 0;
@@ -3508,15 +3575,16 @@
return NULL;
for (i = 0; i < len; i++) {
- PyObject *v = Array_item(self, i+ilow);
+ PyObject *v = Array_item(_self, i+ilow);
PyList_SET_ITEM(np, i, v);
}
return (PyObject *)np;
}
static int
-Array_ass_item(CDataObject *self, int index, PyObject *value)
-{
+Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
+{
+ CDataObject *self = (CDataObject *)_self;
int size, offset;
StgDictObject *stgdict;
char *ptr;
@@ -3542,8 +3610,9 @@
}
static int
-Array_ass_slice(CDataObject *self, int ilow, int ihigh, PyObject *value)
-{
+Array_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *value)
+{
+ CDataObject *self = (CDataObject *)_self;
int i, len;
if (value == NULL) {
@@ -3574,7 +3643,7 @@
int result;
if (item == NULL)
return -1;
- result = Array_ass_item(self, i+ilow, item);
+ result = Array_ass_item(_self, i+ilow, item);
Py_DECREF(item);
if (result == -1)
return -1;
@@ -3582,20 +3651,21 @@
return 0;
}
-static int
-Array_length(CDataObject *self)
-{
+static Py_ssize_t
+Array_length(PyObject *_self)
+{
+ CDataObject *self = (CDataObject *)_self;
return self->b_length;
}
static PySequenceMethods Array_as_sequence = {
- (inquiry)Array_length, /* sq_length; */
+ Array_length, /* sq_length; */
0, /* sq_concat; */
0, /* sq_repeat; */
- (intargfunc)Array_item, /* sq_item; */
- (intintargfunc)Array_slice, /* sq_slice; */
- (intobjargproc)Array_ass_item, /* sq_ass_item; */
- (intintobjargproc)Array_ass_slice, /* sq_ass_slice; */
+ Array_item, /* sq_item; */
+ Array_slice, /* sq_slice; */
+ Array_ass_item, /* sq_ass_item; */
+ Array_ass_slice, /* sq_ass_slice; */
0, /* sq_contains; */
0, /* sq_inplace_concat; */
@@ -3666,7 +3736,7 @@
};
PyObject *
-CreateArrayType(PyObject *itemtype, int length)
+CreateArrayType(PyObject *itemtype, Py_ssize_t length)
{
static PyObject *cache;
PyObject *key;
@@ -3678,7 +3748,11 @@
if (cache == NULL)
return NULL;
}
+#if (PY_VERSION_HEX < 0x02050000)
key = Py_BuildValue("(Oi)", itemtype, length);
+#else
+ key = Py_BuildValue("(On)", itemtype, length);
+#endif
if (!key)
return NULL;
result = PyDict_GetItem(cache, key);
@@ -3693,11 +3767,20 @@
"Expected a type object");
return NULL;
}
- sprintf(name, "%.200s_Array_%d",
+#ifdef MS_WIN64
+ sprintf(name, "%.200s_Array_%Id",
((PyTypeObject *)itemtype)->tp_name, length);
+#else
+ sprintf(name, "%.200s_Array_%ld",
+ ((PyTypeObject *)itemtype)->tp_name, (long)length);
+#endif
result = PyObject_CallFunction((PyObject *)&ArrayType_Type,
+#if (PY_VERSION_HEX < 0x02050000)
"s(O){s:i,s:O}",
+#else
+ "s(O){s:n,s:O}",
+#endif
name,
&Array_Type,
"_length_",
@@ -3871,7 +3954,7 @@
name = PyString_FromString(self->ob_type->tp_name);
if (name == NULL) {
- Py_DECREF(name);
+ Py_DECREF(val);
return NULL;
}
@@ -3934,11 +4017,11 @@
Pointer_Type
*/
static PyObject *
-Pointer_item(CDataObject *self, int index)
-{
+Pointer_item(PyObject *_self, Py_ssize_t index)
+{
+ CDataObject *self = (CDataObject *)_self;
int size, offset;
StgDictObject *stgdict, *itemdict;
- PyObject *base;
PyObject *proto;
if (*(void **)self->b_ptr == NULL) {
@@ -3957,18 +4040,14 @@
size = itemdict->size;
offset = index * itemdict->size;
- /* XXX explain! */
- if (index != 0)
- base = NULL;
- else
- base = (PyObject *)self;
- return CData_get(stgdict->proto, stgdict->getfunc, base,
+ return CData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
index, size, (*(char **)self->b_ptr) + offset);
}
static int
-Pointer_ass_item(CDataObject *self, int index, PyObject *value)
-{
+Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
+{
+ CDataObject *self = (CDataObject *)_self;
int size;
StgDictObject *stgdict;
@@ -4109,12 +4188,13 @@
}
static PyObject *
-Pointer_slice(CDataObject *self, int ilow, int ihigh)
-{
+Pointer_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
+{
+ CDataObject *self = (CDataObject *)_self;
PyListObject *np;
StgDictObject *stgdict, *itemdict;
PyObject *proto;
- int i, len;
+ Py_ssize_t i, len;
if (ilow < 0)
ilow = 0;
@@ -4140,7 +4220,7 @@
return NULL;
for (i = 0; i < len; i++) {
- PyObject *v = Pointer_item(self, i+ilow);
+ PyObject *v = Pointer_item(_self, i+ilow);
PyList_SET_ITEM(np, i, v);
}
return (PyObject *)np;
@@ -4150,9 +4230,9 @@
0, /* inquiry sq_length; */
0, /* binaryfunc sq_concat; */
0, /* intargfunc sq_repeat; */
- (intargfunc)Pointer_item, /* intargfunc sq_item; */
- (intintargfunc)Pointer_slice, /* intintargfunc sq_slice; */
- (intobjargproc)Pointer_ass_item, /* intobjargproc sq_ass_item; */
+ Pointer_item, /* intargfunc sq_item; */
+ Pointer_slice, /* intintargfunc sq_slice; */
+ Pointer_ass_item, /* intobjargproc sq_ass_item; */
0, /* intintobjargproc sq_ass_slice; */
0, /* objobjproc sq_contains; */
/* Added in release 2.0 */
@@ -4326,13 +4406,51 @@
#endif
static PyObject *
-string_at(const char *ptr, int size)
+string_at(const char *ptr, Py_ssize_t size)
{
if (size == 0)
return PyString_FromString(ptr);
return PyString_FromStringAndSize(ptr, size);
}
+static int
+cast_check_pointertype(PyObject *arg)
+{
+ StgDictObject *dict;
+
+ if (PointerTypeObject_Check(arg))
+ return 1;
+ if (CFuncPtrTypeObject_Check(arg))
+ return 1;
+ dict = PyType_stgdict(arg);
+ if (dict) {
+ if (PyString_Check(dict->proto)
+ && (strchr("sPzUZXO", PyString_AS_STRING(dict->proto)[0]))) {
+ /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
+ return 1;
+ }
+ }
+ PyErr_Format(PyExc_TypeError,
+ "cast() argument 2 must be a pointer type, not %s",
+ PyType_Check(arg)
+ ? ((PyTypeObject *)arg)->tp_name
+ : arg->ob_type->tp_name);
+ return 0;
+}
+
+static PyObject *
+cast(void *ptr, PyObject *ctype)
+{
+ CDataObject *result;
+ if (0 == cast_check_pointertype(ctype))
+ return NULL;
+ result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
+ if (result == NULL)
+ return NULL;
+ /* Should we assert that result is a pointer type? */
+ memcpy(result->b_ptr, &ptr, sizeof(void *));
+ return (PyObject *)result;
+}
#ifdef CTYPES_UNICODE
static PyObject *
@@ -4344,7 +4462,7 @@
}
#endif
-DL_EXPORT(void)
+PyMODINIT_FUNC
init_ctypes(void)
{
PyObject *m;
@@ -4463,19 +4581,30 @@
#endif
PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL));
PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI));
- PyModule_AddStringConstant(m, "__version__", "0.9.9.3");
+ PyModule_AddStringConstant(m, "__version__", "0.9.9.6");
PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at));
+ PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast));
#ifdef CTYPES_UNICODE
PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
#endif
-#ifdef RTLD_LOCAL
+/* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
+#ifndef RTLD_LOCAL
+#define RTLD_LOCAL 0
+#endif
+
+/* If RTLD_GLOBAL is not defined (cygwin), set it to the same value as
+ RTLD_LOCAL.
+*/
+#ifndef RTLD_GLOBAL
+#define RTLD_GLOBAL RTLD_LOCAL
+#endif
+
PyModule_AddObject(m, "RTLD_LOCAL", PyInt_FromLong(RTLD_LOCAL));
PyModule_AddObject(m, "RTLD_GLOBAL", PyInt_FromLong(RTLD_GLOBAL));
-#endif
PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
if (PyExc_ArgError) {
Modified: packages/ctypes/trunk/source/_ctypes_test.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/_ctypes_test.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/_ctypes_test.c (original)
+++ packages/ctypes/trunk/source/_ctypes_test.c Mon Jun 19 12:36:05 2006
@@ -51,21 +51,21 @@
*presult = a + b;
}
-EXPORT(int) _testfunc_i_bhilfd(char b, short h, int i, long l, float f, double d)
+EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
// printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
// b, h, i, l, f, d);
return (int)(b + h + i + l + f + d);
}
-EXPORT(float) _testfunc_f_bhilfd(char b, short h, int i, long l, float f, double d)
+EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
// printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
// b, h, i, l, f, d);
return (float)(b + h + i + l + f + d);
}
-EXPORT(double) _testfunc_d_bhilfd(char b, short h, int i, long l, float f, double d)
+EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
// printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
// b, h, i, l, f, d);
@@ -74,7 +74,7 @@
EXPORT(char *) _testfunc_p_p(void *s)
{
- return s;
+ return (char *)s;
}
EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv)
@@ -89,7 +89,7 @@
EXPORT(char *) my_strdup(char *src)
{
- char *dst = malloc(strlen(src)+1);
+ char *dst = (char *)malloc(strlen(src)+1);
if (!dst)
return NULL;
strcpy(dst, src);
@@ -99,8 +99,8 @@
#ifdef HAVE_WCHAR_H
EXPORT(wchar_t *) my_wcsdup(wchar_t *src)
{
- int len = wcslen(src);
- wchar_t *ptr = malloc((len + 1) * sizeof(wchar_t));
+ size_t len = wcslen(src);
+ wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
if (ptr == NULL)
return NULL;
memcpy(ptr, src, (len+1) * sizeof(wchar_t));
@@ -152,13 +152,13 @@
}
#ifdef HAVE_LONG_LONG
-EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(char b, short h, int i, long l, float f,
+EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f,
double d, PY_LONG_LONG q)
{
return (PY_LONG_LONG)(b + h + i + l + f + d + q);
}
-EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(char b, short h, int i, long l, float f, double d)
+EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
return (PY_LONG_LONG)(b + h + i + l + f + d);
}
@@ -191,7 +191,7 @@
{
static char message[] = "Hello, World";
if (p) {
- *p = malloc(sizeof(char *));
+ *p = (char **)malloc(sizeof(char *));
printf("malloc returned %p\n", *p);
**p = message;
return 1;
@@ -385,7 +385,7 @@
#define S last_tf_arg_s = (PY_LONG_LONG)c
#define U last_tf_arg_u = (unsigned PY_LONG_LONG)c
-EXPORT(char) tf_b(char c) { S; return c/3; }
+EXPORT(signed char) tf_b(signed char c) { S; return c/3; }
EXPORT(unsigned char) tf_B(unsigned char c) { U; return c/3; }
EXPORT(short) tf_h(short c) { S; return c/3; }
EXPORT(unsigned short) tf_H(unsigned short c) { U; return c/3; }
@@ -399,7 +399,7 @@
EXPORT(double) tf_d(double c) { S; return c/3; }
#ifdef MS_WIN32
-EXPORT(char) __stdcall s_tf_b(char c) { S; return c/3; }
+EXPORT(signed char) __stdcall s_tf_b(signed char c) { S; return c/3; }
EXPORT(unsigned char) __stdcall s_tf_B(unsigned char c) { U; return c/3; }
EXPORT(short) __stdcall s_tf_h(short c) { S; return c/3; }
EXPORT(unsigned short) __stdcall s_tf_H(unsigned short c) { U; return c/3; }
@@ -414,33 +414,33 @@
#endif
/*******/
-EXPORT(char) tf_bb(char x, char c) { S; return c/3; }
-EXPORT(unsigned char) tf_bB(char x, unsigned char c) { U; return c/3; }
-EXPORT(short) tf_bh(char x, short c) { S; return c/3; }
-EXPORT(unsigned short) tf_bH(char x, unsigned short c) { U; return c/3; }
-EXPORT(int) tf_bi(char x, int c) { S; return c/3; }
-EXPORT(unsigned int) tf_bI(char x, unsigned int c) { U; return c/3; }
-EXPORT(long) tf_bl(char x, long c) { S; return c/3; }
-EXPORT(unsigned long) tf_bL(char x, unsigned long c) { U; return c/3; }
-EXPORT(PY_LONG_LONG) tf_bq(char x, PY_LONG_LONG c) { S; return c/3; }
-EXPORT(unsigned PY_LONG_LONG) tf_bQ(char x, unsigned PY_LONG_LONG c) { U; return c/3; }
-EXPORT(float) tf_bf(char x, float c) { S; return c/3; }
-EXPORT(double) tf_bd(char x, double c) { S; return c/3; }
+EXPORT(signed char) tf_bb(signed char x, signed char c) { S; return c/3; }
+EXPORT(unsigned char) tf_bB(signed char x, unsigned char c) { U; return c/3; }
+EXPORT(short) tf_bh(signed char x, short c) { S; return c/3; }
+EXPORT(unsigned short) tf_bH(signed char x, unsigned short c) { U; return c/3; }
+EXPORT(int) tf_bi(signed char x, int c) { S; return c/3; }
+EXPORT(unsigned int) tf_bI(signed char x, unsigned int c) { U; return c/3; }
+EXPORT(long) tf_bl(signed char x, long c) { S; return c/3; }
+EXPORT(unsigned long) tf_bL(signed char x, unsigned long c) { U; return c/3; }
+EXPORT(PY_LONG_LONG) tf_bq(signed char x, PY_LONG_LONG c) { S; return c/3; }
+EXPORT(unsigned PY_LONG_LONG) tf_bQ(signed char x, unsigned PY_LONG_LONG c) { U; return c/3; }
+EXPORT(float) tf_bf(signed char x, float c) { S; return c/3; }
+EXPORT(double) tf_bd(signed char x, double c) { S; return c/3; }
EXPORT(void) tv_i(int c) { S; return; }
#ifdef MS_WIN32
-EXPORT(char) __stdcall s_tf_bb(char x, char c) { S; return c/3; }
-EXPORT(unsigned char) __stdcall s_tf_bB(char x, unsigned char c) { U; return c/3; }
-EXPORT(short) __stdcall s_tf_bh(char x, short c) { S; return c/3; }
-EXPORT(unsigned short) __stdcall s_tf_bH(char x, unsigned short c) { U; return c/3; }
-EXPORT(int) __stdcall s_tf_bi(char x, int c) { S; return c/3; }
-EXPORT(unsigned int) __stdcall s_tf_bI(char x, unsigned int c) { U; return c/3; }
-EXPORT(long) __stdcall s_tf_bl(char x, long c) { S; return c/3; }
-EXPORT(unsigned long) __stdcall s_tf_bL(char x, unsigned long c) { U; return c/3; }
-EXPORT(PY_LONG_LONG) __stdcall s_tf_bq(char x, PY_LONG_LONG c) { S; return c/3; }
-EXPORT(unsigned PY_LONG_LONG) __stdcall s_tf_bQ(char x, unsigned PY_LONG_LONG c) { U; return c/3; }
-EXPORT(float) __stdcall s_tf_bf(char x, float c) { S; return c/3; }
-EXPORT(double) __stdcall s_tf_bd(char x, double c) { S; return c/3; }
+EXPORT(signed char) __stdcall s_tf_bb(signed char x, signed char c) { S; return c/3; }
+EXPORT(unsigned char) __stdcall s_tf_bB(signed char x, unsigned char c) { U; return c/3; }
+EXPORT(short) __stdcall s_tf_bh(signed char x, short c) { S; return c/3; }
+EXPORT(unsigned short) __stdcall s_tf_bH(signed char x, unsigned short c) { U; return c/3; }
+EXPORT(int) __stdcall s_tf_bi(signed char x, int c) { S; return c/3; }
+EXPORT(unsigned int) __stdcall s_tf_bI(signed char x, unsigned int c) { U; return c/3; }
+EXPORT(long) __stdcall s_tf_bl(signed char x, long c) { S; return c/3; }
+EXPORT(unsigned long) __stdcall s_tf_bL(signed char x, unsigned long c) { U; return c/3; }
+EXPORT(PY_LONG_LONG) __stdcall s_tf_bq(signed char x, PY_LONG_LONG c) { S; return c/3; }
+EXPORT(unsigned PY_LONG_LONG) __stdcall s_tf_bQ(signed char x, unsigned PY_LONG_LONG c) { U; return c/3; }
+EXPORT(float) __stdcall s_tf_bf(signed char x, float c) { S; return c/3; }
+EXPORT(double) __stdcall s_tf_bd(signed char x, double c) { S; return c/3; }
EXPORT(void) __stdcall s_tv_i(int c) { S; return; }
#endif
Modified: packages/ctypes/trunk/source/callbacks.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/callbacks.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/callbacks.c (original)
+++ packages/ctypes/trunk/source/callbacks.c Mon Jun 19 12:36:05 2006
@@ -238,10 +238,24 @@
CHECK("'converting callback result'", keep);
break;
}
- /* assert (keep == Py_None); */
- /* XXX We have no way to keep the needed reference XXX */
- /* Should we emit a warning? */
- Py_XDECREF(keep);
+ /* keep is an object we have to keep alive so that the result
+ stays valid. If there is no such object, the setfunc will
+ have returned Py_None.
+
+ If there is such an object, we have no choice than to keep
+ it alive forever - but a refcount and/or memory leak will
+ be the result. EXCEPT when restype is py_object - Python
+ itself knows how to manage the refcount of these objects.
+ */
+ if (keep == NULL) /* Could not convert callback result. */
+ PyErr_WriteUnraisable(Py_None);
+ else if (keep == Py_None) /* Nothing to keep */
+ Py_DECREF(keep);
+ else if (setfunc != getentry("O")->setfunc) {
+ if (-1 == PyErr_Warn(PyExc_RuntimeWarning,
+ "memory leak in callback function."))
+ PyErr_WriteUnraisable(Py_None);
+ }
}
Py_XDECREF(result);
Done:
@@ -249,16 +263,6 @@
PyGILState_Release(state);
}
-
-typedef struct {
- ffi_closure *pcl; /* the C callable */
- ffi_cif cif;
- PyObject *converters;
- PyObject *callable;
- SETFUNC setfunc;
- ffi_type *restype;
- ffi_type *atypes[0];
-} ffi_info;
static void closure_fcn(ffi_cif *cif,
void *resp,
@@ -275,16 +279,10 @@
args);
}
-void FreeCallback(THUNK thunk)
-{
- FreeClosure(((ffi_info *)thunk)->pcl);
- PyMem_Free(thunk);
-}
-
-THUNK AllocFunctionCallback(PyObject *callable,
- PyObject *converters,
- PyObject *restype,
- int is_cdecl)
+ffi_info *AllocFunctionCallback(PyObject *callable,
+ PyObject *converters,
+ PyObject *restype,
+ int is_cdecl)
{
int result;
ffi_info *p;
@@ -299,13 +297,14 @@
}
p->pcl = MallocClosure();
if (p->pcl == NULL) {
- PyMem_Free(p);
PyErr_NoMemory();
- return NULL;
+ goto error;
}
for (i = 0; i < nArgs; ++i) {
PyObject *cnv = PySequence_GetItem(converters, i);
+ if (cnv == NULL)
+ goto error;
p->atypes[i] = GetType(cnv);
Py_DECREF(cnv);
}
@@ -316,12 +315,10 @@
p->restype = &ffi_type_void;
} else {
StgDictObject *dict = PyType_stgdict(restype);
- if (dict == NULL) {
- PyMem_Free(p);
- return NULL;
- }
+ if (dict == NULL)
+ goto error;
p->setfunc = dict->setfunc;
- p->restype = &dict->ffi_type;
+ p->restype = &dict->ffi_type_pointer;
}
cc = FFI_DEFAULT_ABI;
@@ -335,21 +332,26 @@
if (result != FFI_OK) {
PyErr_Format(PyExc_RuntimeError,
"ffi_prep_cif failed with %d", result);
- PyMem_Free(p);
- return NULL;
+ goto error;
}
result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
if (result != FFI_OK) {
PyErr_Format(PyExc_RuntimeError,
"ffi_prep_closure failed with %d", result);
- PyMem_Free(p);
- return NULL;
+ goto error;
}
p->converters = converters;
p->callable = callable;
-
- return (THUNK)p;
+ return p;
+
+ error:
+ if (p) {
+ if (p->pcl)
+ FreeClosure(p->pcl);
+ PyMem_Free(p);
+ }
+ return NULL;
}
/****************************************************************************
Modified: packages/ctypes/trunk/source/callproc.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/callproc.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/callproc.c (original)
+++ packages/ctypes/trunk/source/callproc.c Mon Jun 19 12:36:05 2006
@@ -60,18 +60,21 @@
#ifdef MS_WIN32
#include <windows.h>
#else
-#include <dlfcn.h>
-#endif
-
-#ifdef MS_WIN32
-#define alloca _alloca
+#include "ctypes_dlfcn.h"
+#endif
+
+#ifdef MS_WIN32
+#include <malloc.h>
#endif
#include <ffi.h>
#include "ctypes.h"
-#ifdef _DEBUG
-#define DEBUG_EXCEPTIONS /* */
+#if defined(_DEBUG) || defined(__MINGW32__)
+/* Don't use structured exception handling on Windows if this is defined.
+ MingW, AFAIK, doesn't support it.
+*/
+#define DONT_USE_SEH
#endif
#ifdef MS_WIN32
@@ -96,6 +99,7 @@
return lpMsgBuf;
}
+#ifndef DONT_USE_SEH
void SetException(DWORD code, EXCEPTION_RECORD *pr)
{
TCHAR *lpMsgBuf;
@@ -254,6 +258,7 @@
*record = *ptrs->ExceptionRecord;
return EXCEPTION_EXECUTE_HANDLER;
}
+#endif
static PyObject *
check_hresult(PyObject *self, PyObject *args)
@@ -576,14 +581,14 @@
/* This little trick works correctly with MSVC.
It returns small structures in registers
*/
- if (dict->ffi_type.type == FFI_TYPE_STRUCT) {
- if (dict->ffi_type.size <= 4)
+ if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
+ if (dict->ffi_type_pointer.size <= 4)
return &ffi_type_sint32;
- else if (dict->ffi_type.size <= 8)
+ else if (dict->ffi_type_pointer.size <= 8)
return &ffi_type_sint64;
}
#endif
- return &dict->ffi_type;
+ return &dict->ffi_type_pointer;
}
@@ -612,8 +617,10 @@
int cc;
#ifdef MS_WIN32
int delta;
+#ifndef DONT_USE_SEH
DWORD dwExceptionCode = 0;
EXCEPTION_RECORD record;
+#endif
#endif
/* XXX check before here */
if (restype == NULL) {
@@ -640,14 +647,14 @@
if ((flags & FUNCFLAG_PYTHONAPI) == 0)
Py_UNBLOCK_THREADS
#ifdef MS_WIN32
-#ifndef DEBUG_EXCEPTIONS
+#ifndef DONT_USE_SEH
__try {
#endif
delta =
#endif
ffi_call(&cif, (void *)pProc, resmem, avalues);
#ifdef MS_WIN32
-#ifndef DEBUG_EXCEPTIONS
+#ifndef DONT_USE_SEH
}
__except (HandleException(GetExceptionInformation(),
&dwExceptionCode, &record)) {
@@ -658,10 +665,12 @@
if ((flags & FUNCFLAG_PYTHONAPI) == 0)
Py_BLOCK_THREADS
#ifdef MS_WIN32
+#ifndef DONT_USE_SEH
if (dwExceptionCode) {
SetException(dwExceptionCode, &record);
return -1;
}
+#endif
if (delta < 0) {
if (flags & FUNCFLAG_CDECL)
PyErr_Format(PyExc_ValueError,
@@ -715,9 +724,16 @@
if (dict == NULL)
return PyObject_CallFunction(restype, "i", *(int *)result);
- if (dict->getfunc && !IsSimpleSubType(restype))
+ if (dict->getfunc && !IsSimpleSubType(restype)) {
retval = dict->getfunc(result, dict->size);
- else
+ /* If restype is py_object (detected by comparing getfunc with
+ O_get), we have to call Py_DECREF because O_get has already
+ called Py_INCREF.
+ */
+ if (dict->getfunc == getentry("O")->getfunc) {
+ Py_DECREF(retval);
+ }
+ } else
retval = CData_FromBaseObj(restype, NULL, 0, result);
if (!checker || !retval)
@@ -751,6 +767,8 @@
if (cls_str) {
PyString_ConcatAndDel(&s, cls_str);
PyString_ConcatAndDel(&s, PyString_FromString(": "));
+ if (s == NULL)
+ goto error;
} else
PyErr_Clear();
msg_str = PyObject_Str(v);
@@ -759,12 +777,15 @@
else {
PyErr_Clear();
PyString_ConcatAndDel(&s, PyString_FromString("???"));
+ if (s == NULL)
+ goto error;
}
PyErr_SetObject(exc_class, s);
+error:
Py_XDECREF(tp);
Py_XDECREF(v);
Py_XDECREF(tb);
- Py_DECREF(s);
+ Py_XDECREF(s);
}
@@ -1155,10 +1176,10 @@
if (!PyArg_ParseTuple(args, "z|i:dlopen", &name, &mode))
return NULL;
mode |= RTLD_NOW;
- handle = dlopen(name, mode);
+ handle = ctypes_dlopen(name, mode);
if (!handle) {
PyErr_SetString(PyExc_OSError,
- dlerror());
+ ctypes_dlerror());
return NULL;
}
return PyLong_FromVoidPtr(handle);
@@ -1172,7 +1193,7 @@
return NULL;
if (dlclose(handle)) {
PyErr_SetString(PyExc_OSError,
- dlerror());
+ ctypes_dlerror());
return NULL;
}
Py_INCREF(Py_None);
@@ -1187,10 +1208,10 @@
if (!PyArg_ParseTuple(args, "is:dlsym", &handle, &name))
return NULL;
- ptr = dlsym(handle, name);
+ ptr = ctypes_dlsym(handle, name);
if (!ptr) {
PyErr_SetString(PyExc_OSError,
- dlerror());
+ ctypes_dlerror());
return NULL;
}
return Py_BuildValue("i", ptr);
@@ -1356,7 +1377,7 @@
converter(PyObject *obj, void **address)
{
*address = PyLong_AsVoidPtr(obj);
- return address != NULL;
+ return *address != NULL;
}
static PyObject *
@@ -1416,71 +1437,7 @@
}
#endif
-static char cast_doc[] =
-"cast(cobject, ctype) -> ctype-instance\n\
-\n\
-Create an instance of ctype, and copy the internal memory buffer\n\
-of cobject to the new instance. Should be used to cast one type\n\
-of pointer to another type of pointer.\n\
-Doesn't work correctly with ctypes integers.\n";
-
-static int cast_check_pointertype(PyObject *arg, PyObject **pobj)
-{
- StgDictObject *dict;
-
- if (PointerTypeObject_Check(arg)) {
- *pobj = arg;
- return 1;
- }
- dict = PyType_stgdict(arg);
- if (dict) {
- if (PyString_Check(dict->proto)
- && (strchr("sPzUZXO", PyString_AS_STRING(dict->proto)[0]))) {
- /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
- *pobj = arg;
- return 1;
- }
- }
- if (PyType_Check(arg)) {
- PyErr_Format(PyExc_TypeError,
- "cast() argument 2 must be a pointer type, not %s",
- ((PyTypeObject *)arg)->tp_name);
- } else {
- PyErr_Format(PyExc_TypeError,
- "cast() argument 2 must be a pointer type, not a %s",
- arg->ob_type->tp_name);
- }
- return 0;
-}
-
-static PyObject *cast(PyObject *self, PyObject *args)
-{
- PyObject *obj, *ctype;
- struct argument a;
- CDataObject *result;
-
- /* We could and should allow array types for the second argument
- also, but we cannot use the simple memcpy below for them. */
- if (!PyArg_ParseTuple(args, "OO&:cast", &obj, &cast_check_pointertype, &ctype))
- return NULL;
- if (-1 == ConvParam(obj, 1, &a))
- return NULL;
- result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
- if (result == NULL) {
- Py_XDECREF(a.keep);
- return NULL;
- }
- // result->b_size
- // a.ffi_type->size
- memcpy(result->b_ptr, &a.value,
- min(result->b_size, (int)a.ffi_type->size));
- Py_XDECREF(a.keep);
- return (PyObject *)result;
-}
-
-
PyMethodDef module_methods[] = {
- {"cast", cast, METH_VARARGS, cast_doc},
#ifdef CTYPES_UNICODE
{"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
#endif
Modified: packages/ctypes/trunk/source/cfield.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/cfield.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/cfield.c (original)
+++ packages/ctypes/trunk/source/cfield.c Mon Jun 19 12:36:05 2006
@@ -245,16 +245,26 @@
PyObject *result;
int bits = self->size >> 16;
int size = self->size & 0xFFFF;
- char *name;
+ const char *name;
name = ((PyTypeObject *)self->proto)->tp_name;
if (bits)
- result = PyString_FromFormat("<Field type=%s, ofs=%d:%d, bits=%d>",
- name, self->offset, size, bits);
+ result = PyString_FromFormat(
+#if (PY_VERSION_HEX < 0x02050000)
+ "<Field type=%s, ofs=%d:%d, bits=%d>",
+#else
+ "<Field type=%s, ofs=%zd:%d, bits=%d>",
+#endif
+ name, self->offset, size, bits);
else
- result = PyString_FromFormat("<Field type=%s, ofs=%d, size=%d>",
- name, self->offset, size);
+ result = PyString_FromFormat(
+#if (PY_VERSION_HEX < 0x02050000)
+ "<Field type=%s, ofs=%d, size=%d>",
+#else
+ "<Field type=%s, ofs=%zd, size=%d>",
+#endif
+ name, self->offset, size);
return result;
}
@@ -489,7 +499,7 @@
long val;
if (get_long(value, &val) < 0)
return NULL;
- *(char *)ptr = (char)SET(*(char *)ptr, (char)val, size);
+ *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size);
_RET(value);
}
@@ -497,7 +507,7 @@
static PyObject *
b_get(void *ptr, unsigned size)
{
- char val = *(char *)ptr;
+ signed char val = *(signed char *)ptr;
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
}
@@ -526,9 +536,12 @@
h_set(void *ptr, PyObject *value, unsigned size)
{
long val;
+ short x;
if (get_long(value, &val) < 0)
return NULL;
- *(short *)ptr = (short)SET(*(short *)ptr, (short)val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (short)val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -540,37 +553,43 @@
short field;
if (get_long(value, &val) < 0)
return NULL;
- field = SWAP_2(*(short *)ptr);
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_2(field);
field = SET(field, (short)val, size);
- *(short *)ptr = SWAP_2(field);
+ field = SWAP_2(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
static PyObject *
h_get(void *ptr, unsigned size)
{
- short val = *(short *)ptr;
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong((long)val);
+}
+
+static PyObject *
+h_get_sw(void *ptr, unsigned size)
+{
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_2(val);
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
}
static PyObject *
-h_get_sw(void *ptr, unsigned size)
-{
- short val = *(short *)ptr;
- val = SWAP_2(val);
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
-}
-
-static PyObject *
H_set(void *ptr, PyObject *value, unsigned size)
{
unsigned long val;
+ unsigned short x;
if (get_ulong(value, &val) < 0)
return NULL;
- *(unsigned short *)ptr = (unsigned short)SET(*(unsigned short *)ptr,
- (unsigned short)val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (unsigned short)val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -581,9 +600,11 @@
unsigned short field;
if (get_ulong(value, &val) < 0)
return NULL;
- field = SWAP_2(*(unsigned short *)ptr);
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_2(field);
field = SET(field, (unsigned short)val, size);
- *(unsigned short *)ptr = SWAP_2(field);
+ field = SWAP_2(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
@@ -591,7 +612,8 @@
static PyObject *
H_get(void *ptr, unsigned size)
{
- unsigned short val = *(unsigned short *)ptr;
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
}
@@ -599,7 +621,8 @@
static PyObject *
H_get_sw(void *ptr, unsigned size)
{
- unsigned short val = *(unsigned short *)ptr;
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
val = SWAP_2(val);
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
@@ -609,9 +632,12 @@
i_set(void *ptr, PyObject *value, unsigned size)
{
long val;
+ int x;
if (get_long(value, &val) < 0)
return NULL;
- *(int *)ptr = (int)SET(*(int *)ptr, (int)val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (int)val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -622,9 +648,11 @@
int field;
if (get_long(value, &val) < 0)
return NULL;
- field = SWAP_INT(*(int *)ptr);
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_INT(field);
field = SET(field, (int)val, size);
- *(int *)ptr = SWAP_INT(field);
+ field = SWAP_INT(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
@@ -632,7 +660,8 @@
static PyObject *
i_get(void *ptr, unsigned size)
{
- int val = *(int *)ptr;
+ int val;
+ memcpy(&val, ptr, sizeof(val));
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
}
@@ -640,7 +669,8 @@
static PyObject *
i_get_sw(void *ptr, unsigned size)
{
- int val = *(int *)ptr;
+ int val;
+ memcpy(&val, ptr, sizeof(val));
val = SWAP_INT(val);
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
@@ -674,9 +704,12 @@
I_set(void *ptr, PyObject *value, unsigned size)
{
unsigned long val;
+ unsigned int x;
if (get_ulong(value, &val) < 0)
return NULL;
- *(unsigned int *)ptr = (unsigned int)SET(*(unsigned int *)ptr, (unsigned int)val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (unsigned int)val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -687,9 +720,10 @@
unsigned int field;
if (get_ulong(value, &val) < 0)
return NULL;
- field = SWAP_INT(*(unsigned int *)ptr);
+ memcpy(&field, ptr, sizeof(field));
field = (unsigned int)SET(field, (unsigned int)val, size);
- *(unsigned int *)ptr = SWAP_INT(field);
+ field = SWAP_INT(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
@@ -697,7 +731,8 @@
static PyObject *
I_get(void *ptr, unsigned size)
{
- unsigned int val = *(unsigned int *)ptr;
+ unsigned int val;
+ memcpy(&val, ptr, sizeof(val));
GET_BITFIELD(val, size);
return PyLong_FromUnsignedLong(val);
}
@@ -705,7 +740,8 @@
static PyObject *
I_get_sw(void *ptr, unsigned size)
{
- unsigned int val = *(unsigned int *)ptr;
+ unsigned int val;
+ memcpy(&val, ptr, sizeof(val));
val = SWAP_INT(val);
GET_BITFIELD(val, size);
return PyLong_FromUnsignedLong(val);
@@ -715,9 +751,12 @@
l_set(void *ptr, PyObject *value, unsigned size)
{
long val;
+ long x;
if (get_long(value, &val) < 0)
return NULL;
- *(long *)ptr = (long)SET(*(long *)ptr, val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -728,9 +767,11 @@
long field;
if (get_long(value, &val) < 0)
return NULL;
- field = SWAP_LONG(*(long *)ptr);
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_LONG(field);
field = (long)SET(field, val, size);
- *(long *)ptr = SWAP_LONG(field);
+ field = SWAP_LONG(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
@@ -738,7 +779,8 @@
static PyObject *
l_get(void *ptr, unsigned size)
{
- long val = *(long *)ptr;
+ long val;
+ memcpy(&val, ptr, sizeof(val));
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
}
@@ -746,7 +788,8 @@
static PyObject *
l_get_sw(void *ptr, unsigned size)
{
- long val = *(long *)ptr;
+ long val;
+ memcpy(&val, ptr, sizeof(val));
val = SWAP_LONG(val);
GET_BITFIELD(val, size);
return PyInt_FromLong(val);
@@ -756,9 +799,12 @@
L_set(void *ptr, PyObject *value, unsigned size)
{
unsigned long val;
+ unsigned long x;
if (get_ulong(value, &val) < 0)
return NULL;
- *(unsigned long *)ptr = (unsigned long)SET(*(unsigned long *)ptr, val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -769,9 +815,11 @@
unsigned long field;
if (get_ulong(value, &val) < 0)
return NULL;
- field = SWAP_LONG(*(unsigned long *)ptr);
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_LONG(field);
field = (unsigned long)SET(field, val, size);
- *(unsigned long *)ptr = SWAP_LONG(field);
+ field = SWAP_LONG(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
@@ -779,7 +827,8 @@
static PyObject *
L_get(void *ptr, unsigned size)
{
- unsigned long val = *(unsigned long *)ptr;
+ unsigned long val;
+ memcpy(&val, ptr, sizeof(val));
GET_BITFIELD(val, size);
return PyLong_FromUnsignedLong(val);
}
@@ -787,7 +836,8 @@
static PyObject *
L_get_sw(void *ptr, unsigned size)
{
- unsigned long val = *(unsigned long *)ptr;
+ unsigned long val;
+ memcpy(&val, ptr, sizeof(val));
val = SWAP_LONG(val);
GET_BITFIELD(val, size);
return PyLong_FromUnsignedLong(val);
@@ -798,9 +848,12 @@
q_set(void *ptr, PyObject *value, unsigned size)
{
PY_LONG_LONG val;
+ PY_LONG_LONG x;
if (get_longlong(value, &val) < 0)
return NULL;
- *(PY_LONG_LONG *)ptr = (PY_LONG_LONG)SET(*(PY_LONG_LONG *)ptr, val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -811,16 +864,19 @@
PY_LONG_LONG field;
if (get_longlong(value, &val) < 0)
return NULL;
- field = SWAP_8(*(PY_LONG_LONG *)ptr);
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_8(field);
field = (PY_LONG_LONG)SET(field, val, size);
- *(PY_LONG_LONG *)ptr = SWAP_8(field);
+ field = SWAP_8(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
static PyObject *
q_get(void *ptr, unsigned size)
{
- PY_LONG_LONG val = *(PY_LONG_LONG *)ptr;
+ PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
GET_BITFIELD(val, size);
return PyLong_FromLongLong(val);
}
@@ -828,7 +884,8 @@
static PyObject *
q_get_sw(void *ptr, unsigned size)
{
- PY_LONG_LONG val = *(PY_LONG_LONG *)ptr;
+ PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
val = SWAP_8(val);
GET_BITFIELD(val, size);
return PyLong_FromLongLong(val);
@@ -838,9 +895,12 @@
Q_set(void *ptr, PyObject *value, unsigned size)
{
unsigned PY_LONG_LONG val;
+ unsigned PY_LONG_LONG x;
if (get_ulonglong(value, &val) < 0)
return NULL;
- *(unsigned PY_LONG_LONG *)ptr = (unsigned PY_LONG_LONG)SET(*(unsigned PY_LONG_LONG *)ptr, val, size);
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
@@ -851,16 +911,19 @@
unsigned PY_LONG_LONG field;
if (get_ulonglong(value, &val) < 0)
return NULL;
- field = SWAP_8(*(unsigned PY_LONG_LONG *)ptr);
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_8(field);
field = (unsigned PY_LONG_LONG)SET(field, val, size);
- *(unsigned PY_LONG_LONG *)ptr = SWAP_8(field);
+ field = SWAP_8(field);
+ memcpy(ptr, &field, sizeof(field));
_RET(value);
}
static PyObject *
Q_get(void *ptr, unsigned size)
{
- unsigned PY_LONG_LONG val = *(unsigned PY_LONG_LONG *)ptr;
+ unsigned PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
GET_BITFIELD(val, size);
return PyLong_FromUnsignedLongLong(val);
}
@@ -868,7 +931,8 @@
static PyObject *
Q_get_sw(void *ptr, unsigned size)
{
- unsigned PY_LONG_LONG val = *(unsigned PY_LONG_LONG *)ptr;
+ unsigned PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
val = SWAP_8(val);
GET_BITFIELD(val, size);
return PyLong_FromUnsignedLongLong(val);
@@ -893,14 +957,16 @@
value->ob_type->tp_name);
return NULL;
}
- *(double *)ptr = x;
+ memcpy(ptr, &x, sizeof(double));
_RET(value);
}
static PyObject *
d_get(void *ptr, unsigned size)
{
- return PyFloat_FromDouble(*(double *)ptr);
+ double val;
+ memcpy(&val, ptr, sizeof(val));
+ return PyFloat_FromDouble(val);
}
static PyObject *
@@ -947,14 +1013,16 @@
value->ob_type->tp_name);
return NULL;
}
- *(float *)ptr = x;
+ memcpy(ptr, &x, sizeof(x));
_RET(value);
}
static PyObject *
f_get(void *ptr, unsigned size)
{
- return PyFloat_FromDouble(*(float *)ptr);
+ float val;
+ memcpy(&val, ptr, sizeof(val));
+ return PyFloat_FromDouble(val);
}
static PyObject *
@@ -989,6 +1057,16 @@
#endif
}
+/*
+ py_object refcounts:
+
+ 1. If we have a py_object instance, O_get must Py_INCREF the returned
+ object, of course. If O_get is called from a function result, no py_object
+ instance is created - so callproc.c::GetResult has to call Py_DECREF.
+
+ 2. The memory block in py_object owns a refcount. So, py_object must call
+ Py_DECREF on destruction. Maybe only when b_needsfree is non-zero.
+*/
static PyObject *
O_get(void *ptr, unsigned size)
{
@@ -1000,12 +1078,14 @@
"PyObject is NULL?");
return NULL;
}
+ Py_INCREF(ob);
return ob;
}
static PyObject *
O_set(void *ptr, PyObject *value, unsigned size)
{
+ /* Hm, does the memory block need it's own refcount or not? */
*(PyObject **)ptr = value;
Py_INCREF(value);
return value;
@@ -1295,6 +1375,7 @@
if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
buffer, PyUnicode_GET_SIZE(value))) {
Py_DECREF(value);
+ Py_DECREF(keep);
return NULL;
}
Py_DECREF(value);
Modified: packages/ctypes/trunk/source/ctypes.h
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/ctypes.h?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/ctypes.h (original)
+++ packages/ctypes/trunk/source/ctypes.h Mon Jun 19 12:36:05 2006
@@ -1,4 +1,8 @@
/******************************************************************/
+
+#if (PY_VERSION_HEX < 0x02050000)
+typedef int Py_ssize_t;
+#endif
#ifndef MS_WIN32
#define max(a, b) ((a) > (b) ? (a) : (b))
@@ -17,8 +21,9 @@
#define PY_LONG_LONG LONG_LONG
#endif
-typedef int (*THUNK)(void);
typedef struct tagCDataObject CDataObject;
+typedef PyObject *(* GETFUNC)(void *, unsigned size);
+typedef PyObject *(* SETFUNC)(void *, PyObject *value, unsigned size);
/* A default buffer in CDataObject, which can be used for small C types. If
this buffer is too small, PyMem_Malloc will be called to create a larger one,
@@ -50,13 +55,23 @@
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
- int b_size; /* size of memory block in bytes */
- int b_length; /* number of references we need */
- int b_index; /* index of this object into base's
+ Py_ssize_t b_size; /* size of memory block in bytes */
+ Py_ssize_t b_length; /* number of references we need */
+ Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* list of references we need to keep */
union value b_value;
};
+
+typedef struct {
+ ffi_closure *pcl; /* the C callable */
+ ffi_cif cif;
+ PyObject *converters;
+ PyObject *callable;
+ SETFUNC setfunc;
+ ffi_type *restype;
+ ffi_type *atypes[0];
+} ffi_info;
typedef struct {
/* First part identical to tagCDataObject */
@@ -64,15 +79,15 @@
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
- int b_size; /* size of memory block in bytes */
- int b_length; /* number of references we need */
- int b_index; /* index of this object into base's
+ Py_ssize_t b_size; /* size of memory block in bytes */
+ Py_ssize_t b_length; /* number of references we need */
+ Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* list of references we need to keep */
union value b_value;
/* end of tagCDataObject, additional fields follow */
- THUNK thunk;
+ ffi_info *thunk;
PyObject *callable;
/* These two fields will override the ones in the type's stgdict if
@@ -94,8 +109,8 @@
#define StgDict_Check(v) PyObject_TypeCheck(v, &StgDict_Type)
extern int StructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct);
-extern int PyType_stginfo(PyTypeObject *self, int *psize, int *palign, int *plength);
-extern int PyObject_stginfo(PyObject *self, int *psize, int *palign, int *plength);
+extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength);
+extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength);
@@ -118,7 +133,7 @@
int pack, int is_big_endian);
extern PyObject *CData_AtAddress(PyObject *type, void *buf);
-extern PyObject *CData_FromBytes(PyObject *type, char *data, int length);
+extern PyObject *CData_FromBytes(PyObject *type, char *data, Py_ssize_t length);
extern PyTypeObject ArrayType_Type;
extern PyTypeObject Array_Type;
@@ -137,21 +152,16 @@
#define StructTypeObject_Check(v) PyObject_TypeCheck(v, &StructType_Type)
extern PyObject *
-CreateArrayType(PyObject *itemtype, int length);
+CreateArrayType(PyObject *itemtype, Py_ssize_t length);
extern void init_callbacks_in_module(PyObject *m);
-extern THUNK AllocFunctionCallback(PyObject *callable,
- PyObject *converters,
- PyObject *restype,
- int stdcall);
-extern void FreeCallback(THUNK);
-
extern PyMethodDef module_methods[];
-typedef PyObject *(* GETFUNC)(void *, unsigned size);
-typedef PyObject *(* SETFUNC)(void *, PyObject *value, unsigned size);
-
+extern ffi_info *AllocFunctionCallback(PyObject *callable,
+ PyObject *converters,
+ PyObject *restype,
+ int stdcall);
/* a table entry describing a predefined ctypes type */
struct fielddesc {
char code;
@@ -164,9 +174,9 @@
typedef struct {
PyObject_HEAD
- int offset;
- int size;
- int index; /* Index into CDataObject's
+ Py_ssize_t offset;
+ Py_ssize_t size;
+ Py_ssize_t index; /* Index into CDataObject's
object array */
PyObject *proto; /* a type or NULL */
GETFUNC getfunc; /* getter function if proto is NULL */
@@ -185,10 +195,10 @@
too much risk to change that now, and there are other fields which doen't
belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?)
*/
- int size; /* number of bytes */
- int align; /* alignment requirements */
- int length; /* number of fields */
- ffi_type ffi_type;
+ Py_ssize_t size; /* number of bytes */
+ Py_ssize_t align; /* alignment requirements */
+ Py_ssize_t length; /* number of fields */
+ ffi_type ffi_type_pointer;
PyObject *proto; /* Only for Pointer/ArrayObject */
SETFUNC setfunc; /* Only for simple objects */
GETFUNC getfunc; /* Only for simple objects */
@@ -298,17 +308,17 @@
extern PyObject *
CData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
- int index, int size, char *ptr);
+ Py_ssize_t index, Py_ssize_t size, char *ptr);
extern int
CData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
- int index, int size, char *ptr);
+ Py_ssize_t index, Py_ssize_t size, char *ptr);
extern void Extend_Error_Info(PyObject *exc_class, char *fmt, ...);
struct basespec {
CDataObject *base;
- int index;
+ Py_ssize_t index;
char *adr;
};
@@ -374,7 +384,7 @@
extern void _AddTraceback(char *, char *, int);
-extern PyObject *CData_FromBaseObj(PyObject *type, PyObject *base, int index, char *adr);
+extern PyObject *CData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr);
/* XXX better name needed! */
extern int IsSimpleSubType(PyObject *obj);
Modified: packages/ctypes/trunk/source/darwin/dlfcn.h
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/darwin/dlfcn.h?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/darwin/dlfcn.h (original)
+++ packages/ctypes/trunk/source/darwin/dlfcn.h Mon Jun 19 12:36:05 2006
@@ -31,6 +31,8 @@
#ifndef _DLFCN_H_
#define _DLFCN_H_
+#include <AvailabilityMacros.h>
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -48,11 +50,21 @@
} Dl_info;
+#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_2
+#warning CTYPES_DARWIN_DLFCN
+#define CTYPES_DARWIN_DLFCN
+extern void * (*ctypes_dlopen)(const char *path, int mode);
+extern void * (*ctypes_dlsym)(void * handle, const char *symbol);
+extern const char * (*ctypes_dlerror)(void);
+extern int (*ctypes_dlclose)(void * handle);
+extern int (*ctypes_dladdr)(const void *, Dl_info *);
+#else
extern void * dlopen(const char *path, int mode);
extern void * dlsym(void * handle, const char *symbol);
extern const char * dlerror(void);
extern int dlclose(void * handle);
-extern int dladdr(void *, Dl_info *);
+extern int dladdr(const void *, Dl_info *);
+#endif
#define RTLD_LAZY 0x1
#define RTLD_NOW 0x2
@@ -61,6 +73,9 @@
#define RTLD_NOLOAD 0x10
#define RTLD_NODELETE 0x80
+/* These are from the Mac OS X 10.4 headers */
+#define RTLD_NEXT ((void *) -1) /* Search subsequent objects. */
+#define RTLD_DEFAULT ((void *) -2) /* Use default search algorithm. */
#ifdef __cplusplus
}
Modified: packages/ctypes/trunk/source/darwin/dlfcn_simple.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/darwin/dlfcn_simple.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/darwin/dlfcn_simple.c (original)
+++ packages/ctypes/trunk/source/darwin/dlfcn_simple.c Mon Jun 19 12:36:05 2006
@@ -37,15 +37,46 @@
#include <stdarg.h>
#include <limits.h>
#include <mach-o/dyld.h>
+#include <AvailabilityMacros.h>
#include "dlfcn.h"
+#ifdef CTYPES_DARWIN_DLFCN
+
#define ERR_STR_LEN 256
+#ifndef MAC_OS_X_VERSION_10_3
+#define MAC_OS_X_VERSION_10_3 1030
+#endif
+
+#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
+#define DARWIN_HAS_DLOPEN
+extern void * dlopen(const char *path, int mode) __attribute__((weak_import));
+extern void * dlsym(void * handle, const char *symbol) __attribute__((weak_import));
+extern const char * dlerror(void) __attribute__((weak_import));
+extern int dlclose(void * handle) __attribute__((weak_import));
+extern int dladdr(const void *, Dl_info *) __attribute__((weak_import));
+#endif /* MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3 */
+
+#ifndef DARWIN_HAS_DLOPEN
+#define dlopen darwin_dlopen
+#define dlsym darwin_dlsym
+#define dlerror darwin_dlerror
+#define dlclose darwin_dlclose
+#define dladdr darwin_dladdr
+#endif
+
+void * (*ctypes_dlopen)(const char *path, int mode);
+void * (*ctypes_dlsym)(void * handle, const char *symbol);
+const char * (*ctypes_dlerror)(void);
+int (*ctypes_dlclose)(void * handle);
+int (*ctypes_dladdr)(const void *, Dl_info *);
+
+#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3
+/* Mac OS X 10.3+ has dlopen, so strip all this dead code to avoid warnings */
+
static void *dlsymIntern(void *handle, const char *symbol);
static const char *error(int setget, const char *str, ...);
-
-
/* Set and get the error string for use by dlerror */
static const char *error(int setget, const char *str, ...)
@@ -74,8 +105,8 @@
return retval;
}
-/* dlopen */
-void *dlopen(const char *path, int mode)
+/* darwin_dlopen */
+static void *darwin_dlopen(const char *path, int mode)
{
void *module = 0;
NSObjectFileImage ofi = 0;
@@ -114,9 +145,9 @@
}
/* dlsymIntern is used by dlsym to find the symbol */
-void *dlsymIntern(void *handle, const char *symbol)
-{
- NSSymbol *nssym = 0;
+static void *dlsymIntern(void *handle, const char *symbol)
+{
+ NSSymbol nssym = 0;
/* If the handle is -1, if is the app global context */
if (handle == (void *)-1)
{
@@ -157,12 +188,12 @@
return NSAddressOfSymbol(nssym);
}
-const char *dlerror(void)
+static const char *darwin_dlerror(void)
{
return error(1, (char *)NULL);
}
-int dlclose(void *handle)
+static int darwin_dlclose(void *handle)
{
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
@@ -180,7 +211,7 @@
/* dlsym, prepend the underscore and call dlsymIntern */
-void *dlsym(void *handle, const char *symbol)
+static void *darwin_dlsym(void *handle, const char *symbol)
{
static char undersym[257]; /* Saves calls to malloc(3) */
int sym_len = strlen(symbol);
@@ -208,3 +239,34 @@
}
return value;
}
+
+static int darwin_dladdr(const void *handle, Dl_info *info) {
+ return 0;
+}
+#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
+
+#if __GNUC__ < 4
+#pragma CALL_ON_LOAD ctypes_dlfcn_init
+#else
+static void __attribute__ ((constructor)) ctypes_dlfcn_init(void);
+static
+#endif
+void ctypes_dlfcn_init(void) {
+ if (dlopen != NULL) {
+ ctypes_dlsym = dlsym;
+ ctypes_dlopen = dlopen;
+ ctypes_dlerror = dlerror;
+ ctypes_dlclose = dlclose;
+ ctypes_dladdr = dladdr;
+ } else {
+#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3
+ ctypes_dlsym = darwin_dlsym;
+ ctypes_dlopen = darwin_dlopen;
+ ctypes_dlerror = darwin_dlerror;
+ ctypes_dlclose = darwin_dlclose;
+ ctypes_dladdr = darwin_dladdr;
+#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
+ }
+}
+
+#endif /* CTYPES_DARWIN_DLFCN */
Modified: packages/ctypes/trunk/source/libffi/configure
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/configure?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/configure (original)
+++ packages/ctypes/trunk/source/libffi/configure Mon Jun 19 12:36:05 2006
@@ -3490,6 +3490,7 @@
i*86-*-beos*) TARGET=X86; TARGETDIR=x86;;
i*86-*-freebsd* | i*86-*-kfreebsd*-gnu) TARGET=X86; TARGETDIR=x86;;
i*86-*-netbsdelf* | i*86-*-knetbsd*-gnu) TARGET=X86; TARGETDIR=x86;;
+i*86-*-openbsd*) TARGET=X86; TARGETDIR=x86;;
i*86-*-rtems*) TARGET=X86; TARGETDIR=x86;;
i*86-*-win32*) TARGET=X86_WIN32; TARGETDIR=x86;;
i*86-*-cygwin*) TARGET=X86_WIN32; TARGETDIR=x86;;
Modified: packages/ctypes/trunk/source/libffi/configure.ac
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/configure.ac?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/configure.ac (original)
+++ packages/ctypes/trunk/source/libffi/configure.ac Mon Jun 19 12:36:05 2006
@@ -28,6 +28,7 @@
i*86-*-beos*) TARGET=X86; TARGETDIR=x86;;
i*86-*-freebsd* | i*86-*-kfreebsd*-gnu) TARGET=X86; TARGETDIR=x86;;
i*86-*-netbsdelf* | i*86-*-knetbsd*-gnu) TARGET=X86; TARGETDIR=x86;;
+i*86-*-openbsd*) TARGET=X86; TARGETDIR=x86;;
i*86-*-rtems*) TARGET=X86; TARGETDIR=x86;;
i*86-*-win32*) TARGET=X86_WIN32; TARGETDIR=x86;;
i*86-*-cygwin*) TARGET=X86_WIN32; TARGETDIR=x86;;
Modified: packages/ctypes/trunk/source/libffi/fficonfig.py.in
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/fficonfig.py.in?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/fficonfig.py.in (original)
+++ packages/ctypes/trunk/source/libffi/fficonfig.py.in Mon Jun 19 12:36:05 2006
@@ -32,5 +32,6 @@
ffi_sources = [os.path.join('@srcdir@', f) for f in ffi_sources]
ffi_cflags = '@CFLAGS@'
+# I think this may no longer be needed:
if sys.platform == "openbsd3":
ffi_cflags += " -fno-stack-protector"
Modified: packages/ctypes/trunk/source/libffi/include/ffi.h.in
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/include/ffi.h.in?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/include/ffi.h.in (original)
+++ packages/ctypes/trunk/source/libffi/include/ffi.h.in Mon Jun 19 12:36:05 2006
@@ -188,7 +188,7 @@
} ffi_raw;
void ffi_raw_call (/*@dependent@*/ ffi_cif *cif,
- void (*fn)(),
+ void (*fn)(void),
/*@out@*/ void *rvalue,
/*@dependent@*/ ffi_raw *avalue);
@@ -201,7 +201,7 @@
/* longs and doubles are followed by an empty 64-bit word. */
void ffi_java_raw_call (/*@dependent@*/ ffi_cif *cif,
- void (*fn)(),
+ void (*fn)(void),
/*@out@*/ void *rvalue,
/*@dependent@*/ ffi_raw *avalue);
@@ -270,7 +270,7 @@
/*@dependent@*/ ffi_type **atypes);
void ffi_call(/*@dependent@*/ ffi_cif *cif,
- void (*fn)(),
+ void (*fn)(void),
/*@out@*/ void *rvalue,
/*@dependent@*/ void **avalue);
Modified: packages/ctypes/trunk/source/libffi/src/alpha/osf.S
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/src/alpha/osf.S?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/src/alpha/osf.S (original)
+++ packages/ctypes/trunk/source/libffi/src/alpha/osf.S Mon Jun 19 12:36:05 2006
@@ -3,7 +3,7 @@
Alpha/OSF Foreign Function Interface
- $Id: osf.S,v 1.1.2.2 2006/02/01 20:31:51 perky Exp $
+ $Id: osf.S,v 1.2 2006/03/03 20:24:26 theller Exp $
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
Modified: packages/ctypes/trunk/source/libffi/src/frv/eabi.S
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/src/frv/eabi.S?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/src/frv/eabi.S (original)
+++ packages/ctypes/trunk/source/libffi/src/frv/eabi.S Mon Jun 19 12:36:05 2006
@@ -3,7 +3,7 @@
FR-V Assembly glue.
- $Id: eabi.S,v 1.1.2.4 2006/02/01 20:31:51 perky Exp $
+ $Id: eabi.S,v 1.2 2006/03/03 20:24:46 theller Exp $
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
Modified: packages/ctypes/trunk/source/libffi/src/powerpc/darwin_closure.S
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/src/powerpc/darwin_closure.S?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/src/powerpc/darwin_closure.S (original)
+++ packages/ctypes/trunk/source/libffi/src/powerpc/darwin_closure.S Mon Jun 19 12:36:05 2006
@@ -246,7 +246,7 @@
/* END(ffi_closure_ASM) */
.data
-.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
+.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms
EH_frame1:
.set L$set$0,LECIE1-LSCIE1
.long L$set$0 ; Length of Common Information Entry
Modified: packages/ctypes/trunk/source/libffi/src/x86/ffi.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/libffi/src/x86/ffi.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/libffi/src/x86/ffi.c (original)
+++ packages/ctypes/trunk/source/libffi/src/x86/ffi.c Mon Jun 19 12:36:05 2006
@@ -121,7 +121,7 @@
switch (cif->rtype->type)
{
case FFI_TYPE_VOID:
-#ifndef X86_WIN32
+#if !defined(X86_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__)
case FFI_TYPE_STRUCT:
#endif
case FFI_TYPE_SINT64:
@@ -135,7 +135,7 @@
cif->flags = FFI_TYPE_SINT64;
break;
-#ifdef X86_WIN32
+#if defined(X86_WIN32) || defined(__OpenBSD__) || defined(__FreeBSD__)
case FFI_TYPE_STRUCT:
if (cif->rtype->size == 1)
{
Modified: packages/ctypes/trunk/source/stgdict.c
URL: http://svn.debian.org/wsvn/python-modules/packages/ctypes/trunk/source/stgdict.c?rev=942&op=diff
==============================================================================
--- packages/ctypes/trunk/source/stgdict.c (original)
+++ packages/ctypes/trunk/source/stgdict.c Mon Jun 19 12:36:05 2006
@@ -38,7 +38,7 @@
StgDict_dealloc(StgDictObject *self)
{
StgDict_clear(self);
- PyMem_Free(self->ffi_type.elements);
+ PyMem_Free(self->ffi_type_pointer.elements);
PyDict_Type.tp_dealloc((PyObject *)self);
}
@@ -49,8 +49,8 @@
int size;
StgDict_clear(dst);
- PyMem_Free(dst->ffi_type.elements);
- dst->ffi_type.elements = NULL;
+ PyMem_Free(dst->ffi_type_pointer.elements);
+ dst->ffi_type_pointer.elements = NULL;
d = (char *)dst;
s = (char *)src;
@@ -64,13 +64,15 @@
Py_XINCREF(dst->restype);
Py_XINCREF(dst->checker);
- if (src->ffi_type.elements == NULL)
+ if (src->ffi_type_pointer.elements == NULL)
return 0;
size = sizeof(ffi_type *) * (src->length + 1);
- dst->ffi_type.elements = PyMem_Malloc(size);
- if (dst->ffi_type.elements == NULL)
- return -1;
- memcpy(dst->ffi_type.elements, src->ffi_type.elements, size);
+ dst->ffi_type_pointer.elements = PyMem_Malloc(size);
+ if (dst->ffi_type_pointer.elements == NULL)
+ return -1;
+ memcpy(dst->ffi_type_pointer.elements,
+ src->ffi_type_pointer.elements,
+ size);
return 0;
}
@@ -234,8 +236,8 @@
stuff is sucessfully finished. */
stgdict->flags |= DICTFLAG_FINAL; /* set final */
- if (stgdict->ffi_type.elements)
- PyMem_Free(stgdict->ffi_type.elements);
+ if (stgdict->ffi_type_pointer.elements)
+ PyMem_Free(stgdict->ffi_type_pointer.elements);
basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
if (basedict && !use_broken_old_ctypes_semantics) {
@@ -243,10 +245,12 @@
align = basedict->align;
union_size = 0;
total_align = align ? align : 1;
- stgdict->ffi_type.type = FFI_TYPE_STRUCT;
- stgdict->ffi_type.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
- memset(stgdict->ffi_type.elements, 0, sizeof(ffi_type *) * (basedict->length + len + 1));
- memcpy(stgdict->ffi_type.elements, basedict->ffi_type.elements,
+ stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
+ stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
+ memset(stgdict->ffi_type_pointer.elements, 0,
+ sizeof(ffi_type *) * (basedict->length + len + 1));
+ memcpy(stgdict->ffi_type_pointer.elements,
+ basedict->ffi_type_pointer.elements,
sizeof(ffi_type *) * (basedict->length));
ffi_ofs = basedict->length;
} else {
@@ -255,9 +259,10 @@
align = 0;
union_size = 0;
total_align = 1;
- stgdict->ffi_type.type = FFI_TYPE_STRUCT;
- stgdict->ffi_type.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
- memset(stgdict->ffi_type.elements, 0, sizeof(ffi_type *) * (len + 1));
+ stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
+ stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
+ memset(stgdict->ffi_type_pointer.elements, 0,
+ sizeof(ffi_type *) * (len + 1));
ffi_ofs = 0;
}
@@ -283,10 +288,10 @@
i);
return -1;
}
- stgdict->ffi_type.elements[ffi_ofs + i] = &dict->ffi_type;
+ stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
dict->flags |= DICTFLAG_FINAL; /* mark field type final */
if (PyTuple_Size(pair) == 3) { /* bits specified */
- switch(dict->ffi_type.type) {
+ switch(dict->ffi_type_pointer.type) {
case FFI_TYPE_UINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_UINT32:
@@ -357,8 +362,8 @@
/* Adjust the size according to the alignment requirements */
size = ((size + total_align - 1) / total_align) * total_align;
- stgdict->ffi_type.alignment = total_align;
- stgdict->ffi_type.size = size;
+ stgdict->ffi_type_pointer.alignment = total_align;
+ stgdict->ffi_type_pointer.size = size;
stgdict->size = size;
stgdict->align = total_align;
More information about the Python-modules-commits
mailing list