Exemplo n.º 1
0
 def test_union(self):
     import _rawffi
     longsize = _rawffi.sizeof('l')
     S = _rawffi.Structure([('x', 'h'), ('y', 'l')], union=True)
     s = S(autofree=False)
     s.x = 12345
     lib = _rawffi.CDLL(self.lib_name)
     f = lib.ptr('ret_un_func', [(S, 1)], (S, 1))
     ret = f(s)
     assert ret.y == 1234500, "ret.y == %d" % (ret.y,)
     s.free()
Exemplo n.º 2
0
 def test_union(self):
     import _rawffi
     longsize = _rawffi.sizeof('l')
     S = _rawffi.Structure([('x', 'h'), ('y', 'l')], union=True)
     s = S(autofree=False)
     s.x = 12345
     lib = _rawffi.CDLL(self.lib_name)
     f = lib.ptr('ret_un_func', [(S, 1)], (S, 1))
     ret = f(s)
     assert ret.y == 1234500, "ret.y == %d" % (ret.y, )
     s.free()
Exemplo n.º 3
0
 def test_unicode_array(self):
     import _rawffi
     A = _rawffi.Array('u')
     a = A(6, u'\u1234')
     assert a[0] == u'\u1234'
     a[0] = u'\ud800'
     assert a[0] == u'\ud800'
     if _rawffi.sizeof('u') == 4:
         a[0] = u'\U00012345'
         assert a[0] == u'\U00012345'
         B = _rawffi.Array('i')
         b = B.fromaddress(a.itemaddress(0), 1)
         b[0] = 0xffffffff
         raises(ValueError, "a[0]")
     a.free()
Exemplo n.º 4
0
 def test_wcharp2rawunicode(self):
     import _rawffi
     A = _rawffi.Array('i')
     arg = A(1)
     arg[0] = 0x1234
     u = _rawffi.wcharp2rawunicode(arg.itemaddress(0))
     assert u == u'\u1234'
     u = _rawffi.wcharp2rawunicode(arg.itemaddress(0), 1)
     assert u == u'\u1234'
     arg[0] = -1
     if _rawffi.sizeof('u') == 4:
         raises(ValueError, _rawffi.wcharp2rawunicode, arg.itemaddress(0))
         raises(ValueError, _rawffi.wcharp2rawunicode, arg.itemaddress(0), 1)
         arg[0] = 0x110000
         raises(ValueError, _rawffi.wcharp2rawunicode, arg.itemaddress(0))
         raises(ValueError, _rawffi.wcharp2rawunicode, arg.itemaddress(0), 1)
     arg.free()
Exemplo n.º 5
0
 def test_wide_char(self):
     import _rawffi, sys
     A = _rawffi.Array('u')
     a = A(3)
     a[0] = u'x'
     a[1] = u'y'
     a[2] = u'z'
     assert a[0] == u'x'
     b = _rawffi.Array('c').fromaddress(a.buffer, 38)
     if _rawffi.sizeof('u') == 4:
         # UCS4 build
         if sys.byteorder == 'big':
             assert b[0:8] == b'\x00\x00\x00x\x00\x00\x00y'
         else:
             assert b[0:5] == b'x\x00\x00\x00y'
     else:
         # UCS2 build
         print(b[0:4])
         assert b[0:4] == b'x\x00y\x00'
     a.free()
Exemplo n.º 6
0
 def __new__(self, name, cls, typedict):
     d = dict(
         size       = _rawffi.sizeof('P'),
         align      = _rawffi.alignment('P'),
         length     = 1,
         _ffiargshape_ = 'P',
         _ffishape_  = 'P',
         _fficompositesize_ = None,
     )
     # XXX check if typedict['_type_'] is any sane
     # XXX remember about paramfunc
     obj = type.__new__(self, name, cls, typedict)
     for k, v in d.iteritems():
         setattr(obj, k, v)
     if '_type_' in typedict:
         self.set_type(obj, typedict['_type_'])
     else:
         def __init__(self, value=None):
             raise TypeError("%s has no type" % obj)
         obj.__init__ = __init__
     return obj
Exemplo n.º 7
0
 def _sizeofinstances(self):
     return _rawffi.sizeof('P')
Exemplo n.º 8
0
 def test_sizes_and_alignments(self):
     import _rawffi
     for k, (s, a) in self.sizes_and_alignments.iteritems():
         print k, s, a
         assert _rawffi.sizeof(k) == s
         assert _rawffi.alignment(k) == a
Exemplo n.º 9
0
 def _sizeofinstances(self):
     return _rawffi.sizeof(self._type_)
Exemplo n.º 10
0
    def __new__(self, name, bases, dct):
        try:
            tp = dct['_type_']
        except KeyError:
            for base in bases:
                if hasattr(base, '_type_'):
                    tp = base._type_
                    break
            else:
                raise AttributeError("cannot find _type_ attribute")
        if tp == 'abstract':
            tp = 'i'
        if (not isinstance(tp, str) or not len(tp) == 1
                or tp not in SIMPLE_TYPE_CHARS):
            raise ValueError('%s is not a type character' % (tp))
        default = TP_TO_DEFAULT[tp]
        ffiarray = _rawffi.Array(tp)
        result = type.__new__(self, name, bases, dct)
        result._ffiargshape_ = tp
        result._ffishape_ = tp
        result._fficompositesize_ = None
        result._ffiarray = ffiarray
        if tp in CTYPES_TO_PEP3118_TABLE:
            pep_code = CTYPES_TO_PEP3118_TABLE[tp][_rawffi.sizeof(tp)]
        else:
            pep_code = tp
        result._format = byteorder[sys.byteorder] + pep_code
        if tp == 'z':
            # c_char_p
            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                else:
                    return _rawffi.charp2string(addr)

            def _setvalue(self, value):
                if isinstance(value, basestring):
                    if isinstance(value, unicode):
                        value = value.encode(ConvMode.encoding,
                                             ConvMode.errors)
                    #self._objects = value
                    array = _rawffi.Array('c')(len(value) + 1, value)
                    self._objects = CArgObject(value, array)
                    value = array.buffer
                elif value is None:
                    value = 0
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)
            result._ffiargtype = _ffi.types.Pointer(_ffi.types.char)

        elif tp == 'Z':
            # c_wchar_p
            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                else:
                    return _rawffi.wcharp2unicode(addr)

            def _setvalue(self, value):
                if isinstance(value, basestring):
                    if isinstance(value, str):
                        value = value.decode(ConvMode.encoding,
                                             ConvMode.errors)
                    #self._objects = value
                    array = _rawffi.Array('u')(len(value) + 1, value)
                    self._objects = CArgObject(value, array)
                    value = array.buffer
                elif value is None:
                    value = 0
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)
            result._ffiargtype = _ffi.types.Pointer(_ffi.types.unichar)

        elif tp == 'P':
            # c_void_p

            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                return addr

            def _setvalue(self, value):
                if isinstance(value, str):
                    array = _rawffi.Array('c')(len(value) + 1, value)
                    self._objects = CArgObject(value, array)
                    value = array.buffer
                elif value is None:
                    value = 0
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)

        elif tp == 'u':

            def _setvalue(self, val):
                if isinstance(val, str):
                    val = val.decode(ConvMode.encoding, ConvMode.errors)
                # possible if we use 'ignore'
                if val:
                    self._buffer[0] = val

            def _getvalue(self):
                return self._buffer[0]

            result.value = property(_getvalue, _setvalue)

        elif tp == 'c':

            def _setvalue(self, val):
                if isinstance(val, unicode):
                    val = val.encode(ConvMode.encoding, ConvMode.errors)
                if val:
                    self._buffer[0] = val

            def _getvalue(self):
                return self._buffer[0]

            result.value = property(_getvalue, _setvalue)

        elif tp == 'O':

            def _setvalue(self, val):
                num = pyobj_container.add(val)
                self._buffer[0] = num

            def _getvalue(self):
                return pyobj_container.get(self._buffer[0])

            result.value = property(_getvalue, _setvalue)

        elif tp == 'X':
            from ctypes import WinDLL
            # Use WinDLL("oleaut32") instead of windll.oleaut32
            # because the latter is a shared (cached) object; and
            # other code may set their own restypes. We need out own
            # restype here.
            oleaut32 = WinDLL("oleaut32")
            SysAllocStringLen = oleaut32.SysAllocStringLen
            SysStringLen = oleaut32.SysStringLen
            SysFreeString = oleaut32.SysFreeString

            def _getvalue(self):
                addr = self._buffer[0]
                if addr == 0:
                    return None
                else:
                    size = SysStringLen(addr)
                    return _rawffi.wcharp2rawunicode(addr, size)

            def _setvalue(self, value):
                if isinstance(value, basestring):
                    if isinstance(value, str):
                        value = value.decode(ConvMode.encoding,
                                             ConvMode.errors)
                    array = _rawffi.Array('u')(len(value) + 1, value)
                    value = SysAllocStringLen(array.buffer, len(value))
                elif value is None:
                    value = 0
                if self._buffer[0]:
                    SysFreeString(self._buffer[0])
                self._buffer[0] = value

            result.value = property(_getvalue, _setvalue)

        elif tp == '?':  # regular bool

            def _getvalue(self):
                return bool(self._buffer[0])

            def _setvalue(self, value):
                self._buffer[0] = bool(value)

            result.value = property(_getvalue, _setvalue)

        elif tp == 'v':  # VARIANT_BOOL type

            def _getvalue(self):
                return bool(self._buffer[0])

            def _setvalue(self, value):
                if value:
                    self._buffer[0] = -1  # VARIANT_TRUE
                else:
                    self._buffer[0] = 0  # VARIANT_FALSE

            result.value = property(_getvalue, _setvalue)

        # make pointer-types compatible with the _ffi fast path
        if result._is_pointer_like():

            def _as_ffi_pointer_(self, ffitype):
                return as_ffi_pointer(self, ffitype)

            result._as_ffi_pointer_ = _as_ffi_pointer_
        if name[-2:] != '_p' and name[-3:] not in ('_le', '_be') \
                and name not in ('c_wchar', '_SimpleCData', 'c_longdouble', 'c_bool', 'py_object'):
            if sys.byteorder == 'big':
                name += '_le'
                swapped = self.__new__(self, name, bases, dct)
                result.__ctype_le__ = swapped
                result.__ctype_be__ = result
                swapped.__ctype_be__ = result
                swapped.__ctype_le__ = swapped
                swapped._format = '<' + pep_code
            else:
                name += '_be'
                swapped = self.__new__(self, name, bases, dct)
                result.__ctype_be__ = swapped
                result.__ctype_le__ = result
                swapped.__ctype_le__ = result
                swapped.__ctype_be__ = swapped
                swapped._format = '>' + pep_code
            from _ctypes import sizeof

            def _getval(self):
                return swap_bytes(self._buffer[0], sizeof(self), name, 'get')

            def _setval(self, value):
                d = result()
                d.value = value
                self._buffer[0] = swap_bytes(d.value, sizeof(self), name,
                                             'set')

            swapped.value = property(_getval, _setval)

        return result
Exemplo n.º 11
0
 def _sizeofinstances(self):
     return _rawffi.sizeof('P')
Exemplo n.º 12
0
 def test_sizes_and_alignments(self):
     import _rawffi
     for k, (s, a) in self.sizes_and_alignments.iteritems():
         print k,s,a
         assert _rawffi.sizeof(k) == s
         assert _rawffi.alignment(k) == a
Exemplo n.º 13
0
 def _sizeofinstances(self):
     return _rawffi.sizeof(self._type_)