Exemple #1
0
 def from_param(self, value):
     # array accepts very strange parameters as part of structure
     # or function argument...
     from ctypes import c_char, c_wchar
     if issubclass(self._type_, c_char):
         if isinstance(value, bytes):
             if len(value) > self._length_:
                 raise ValueError("Invalid length")
             value = self(*value)
         elif not isinstance(value, self):
             raise TypeError("expected bytes, %s found" %
                             (value.__class__.__name__, ))
     elif issubclass(self._type_, c_wchar):
         if isinstance(value, str):
             if len(value) > self._length_:
                 raise ValueError("Invalid length")
             value = self(*value)
         elif not isinstance(value, self):
             raise TypeError("expected unicode string, %s found" %
                             (value.__class__.__name__, ))
     else:
         if isinstance(value, tuple):
             if len(value) > self._length_:
                 raise RuntimeError("Invalid length")
             value = self(*value)
     return _CDataMeta.from_param(self, value)
Exemple #2
0
class StructOrUnionMeta(_CDataMeta):
    def __new__(self, name, cls, typedict):
        res = type.__new__(self, name, cls, typedict)
        if hasattr(res, '_swappedbytes_') and '_fields_' in typedict:
            # Activate the stdlib ctypes._swapped_meta.__setattr__ to convert fields
            tmp = res._fields_
            delattr(res, '_fields_')
            setattr(res, '_fields_', tmp)
        if "_abstract_" in typedict:
            return res
        cls = cls or (object, )
        if isinstance(cls[0], StructOrUnionMeta):
            cls[0]._make_final()
        if '_pack_' in typedict:
            if not 0 <= typedict['_pack_'] < 2**31:
                raise ValueError("_pack_ must be a non-negative integer")
        if '_fields_' in typedict:
            if not hasattr(typedict.get('_anonymous_', []), '__iter__'):
                raise TypeError("Anonymous field must be iterable")
            for item in typedict.get('_anonymous_', []):
                if item not in dict(typedict['_fields_']):
                    raise AttributeError("Anonymous field not found")
            names_and_fields(res, typedict['_fields_'], cls[0],
                             typedict.get('_anonymous_', None))
        return res

    def _make_final(self):
        if self is StructOrUnion:
            return
        if '_fields_' not in self.__dict__:
            self._fields_ = []  # As a side-effet, this also sets the ffishape.

    __setattr__ = struct_setattr

    def from_address(self, address):
        instance = StructOrUnion.__new__(self)
        if isinstance(address, _rawffi.StructureInstance):
            address = address.buffer
        # fix the address: turn it into as unsigned, in case it is negative
        address = address & (sys.maxint * 2 + 1)
        instance.__dict__['_buffer'] = self._ffistruct_.fromaddress(address)
        return instance

    def _sizeofinstances(self):
        if not hasattr(self, '_ffistruct_'):
            return 0
        return self._ffistruct_.size

    def _alignmentofinstances(self):
        return self._ffistruct_.alignment

    def from_param(self, value):
        if isinstance(value, tuple):
            try:
                value = self(*value)
            except Exception, e:
                # XXX CPython does not even respect the exception type
                raise RuntimeError("(%s) %s: %s" % (self.__name__, type(e), e))
        return _CDataMeta.from_param(self, value)
Exemple #3
0
 def from_param(self, value):
     if isinstance(value, tuple):
         try:
             value = self(*value)
         except Exception as e:
             # XXX CPython does not even respect the exception type
             raise RuntimeError("(%s) %s: %s" % (self.__name__, type(e), e))
     return _CDataMeta.from_param(self, value)
Exemple #4
0
 def from_param(self, value):
     if isinstance(value, tuple):
         try:
             value = self(*value)
         except Exception as e:
             # XXX CPython does not even respect the exception type
             raise RuntimeError("(%s) %s: %s" % (self.__name__, type(e), e))
     return _CDataMeta.from_param(self, value)
Exemple #5
0
class StructOrUnionMeta(_CDataMeta):

    def __new__(self, name, cls, typedict):
        res = type.__new__(self, name, cls, typedict)
        if "_abstract_" in typedict:
            return res
        cls = cls or (object,)
        if isinstance(cls[0], StructOrUnionMeta):
            cls[0]._make_final()
        if '_fields_' in typedict:
            if not hasattr(typedict.get('_anonymous_', []), '__iter__'):
                raise TypeError("Anonymous field must be iterable")
            for item in typedict.get('_anonymous_', []):
                if item not in dict(typedict['_fields_']):
                    raise AttributeError("Anonymous field not found")
            names_and_fields(
                res,
                typedict['_fields_'], cls[0],
                typedict.get('_anonymous_', None))

        return res

    def _make_final(self):
        if self is StructOrUnion:
            return
        if '_fields_' not in self.__dict__:
            self._fields_ = []
            self._names = []
            self._fieldtypes = {}
            _set_shape(self, [], self._is_union)

    __getattr__ = struct_getattr
    __setattr__ = struct_setattr

    def from_address(self, address):
        instance = StructOrUnion.__new__(self)
        instance.__dict__['_buffer'] = self._ffistruct.fromaddress(address)
        return instance

    def _sizeofinstances(self):
        if not hasattr(self, '_ffistruct'):
            return 0
        return self._ffistruct.size

    def _alignmentofinstances(self):
        return self._ffistruct.alignment

    def from_param(self, value):
        if isinstance(value, tuple):
            try:
                value = self(*value)
            except Exception, e:
                # XXX CPython does not even respect the exception type
                raise RuntimeError("(%s) %s: %s" % (self.__name__, type(e), e))
        return _CDataMeta.from_param(self, value)
 def from_param(self, value):
     if value is None:
         return self(None)
     # If we expect POINTER(<type>), but receive a <type> instance, accept
     # it by calling byref(<type>).
     if isinstance(value, self._type_):
         return byref(value)
     # Array instances are also pointers when the item types are the same.
     if isinstance(value, (_Pointer, Array)):
         if issubclass(type(value)._type_, self._type_):
             return value
     return _CDataMeta.from_param(self, value)
Exemple #7
0
 def from_param(self, value):
     # array accepts very strange parameters as part of structure
     # or function argument...
     from ctypes import c_char, c_wchar
     if issubclass(self._type_, (c_char, c_wchar)):
         if isinstance(value, basestring):
             if len(value) > self._length_:
                 raise ValueError("Invalid length")
             value = self(*value)
     else:
         if isinstance(value, tuple):
             if len(value) > self._length_:
                 raise RuntimeError("Invalid length")
             value = self(*value)
     return _CDataMeta.from_param(self, value)
Exemple #8
0
 def from_param(self, value):
     # array accepts very strange parameters as part of structure
     # or function argument...
     from ctypes import c_char, c_wchar
     if issubclass(self._type_, (c_char, c_wchar)):
         if isinstance(value, basestring):
             if len(value) > self._length_:
                 raise ValueError("Invalid length")
             value = self(*value)
     else:
         if isinstance(value, tuple):
             if len(value) > self._length_:
                 raise RuntimeError("Invalid length")
             value = self(*value)
     return _CDataMeta.from_param(self, value)
 def from_param(self, value):
     # array accepts very strange parameters as part of structure
     # or function argument...
     from ctypes import c_char, c_wchar
     if issubclass(self._type_, (c_char, c_wchar)):
         if isinstance(value, basestring):
             if len(value) > self._length_:
                 raise ValueError("Invalid length")
             value = self(*value)
         elif not isinstance(value, self):
             raise TypeError("expected string or Unicode object, %s found"
                             % (value.__class__.__name__,))
     else:
         if isinstance(value, tuple):
             if len(value) > self._length_:
                 raise RuntimeError("Invalid length")
             value = self(*value)
     return _CDataMeta.from_param(self, value)
Exemple #10
0
 def from_param(self, value):
     # array accepts very strange parameters as part of structure
     # or function argument...
     from ctypes import c_char, c_wchar
     if issubclass(self._type_, (c_char, c_wchar)):
         # XXX: this should maybe be stricer for py3 (c_char disallowing str?)
         if isinstance(value, (bytes, str)):
             if len(value) > self._length_:
                 raise ValueError("Invalid length")
             value = self(*value)
         elif not isinstance(value, self):
             raise TypeError("expected string, %s found" %
                             (value.__class__.__name__, ))
     else:
         if isinstance(value, tuple):
             if len(value) > self._length_:
                 raise RuntimeError("Invalid length")
             value = self(*value)
     return _CDataMeta.from_param(self, value)
Exemple #11
0
 def from_param(self, value):
     # array accepts very strange parameters as part of structure
     # or function argument...
     from ctypes import c_char, c_wchar
     if issubclass(self._type_, (c_char, c_wchar)):
          # XXX: this should maybe be stricer for py3 (c_char disallowing str?)
         if isinstance(value, (bytes, str)):
             if len(value) > self._length_:
                 raise ValueError("Invalid length")
             value = self(*value)
         elif not isinstance(value, self):
             raise TypeError("expected string, %s found"
                             % (value.__class__.__name__,))
     else:
         if isinstance(value, tuple):
             if len(value) > self._length_:
                 raise RuntimeError("Invalid length")
             value = self(*value)
     return _CDataMeta.from_param(self, value)
Exemple #12
0
 def from_param(self, value):
     if isinstance(value, tuple):
         value = self(*value)
     return _CDataMeta.from_param(self, value)
Exemple #13
0
 def from_param(self, value):
     if isinstance(value, tuple):
         value = self(*value)
     return _CDataMeta.from_param(self, value)