当前位置: 首页>>代码示例>>Python>>正文


Python ctypes.Structure方法代码示例

本文整理汇总了Python中ctypes.Structure方法的典型用法代码示例。如果您正苦于以下问题:Python ctypes.Structure方法的具体用法?Python ctypes.Structure怎么用?Python ctypes.Structure使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ctypes的用法示例。


在下文中一共展示了ctypes.Structure方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: windowsRam

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def windowsRam(self):
        """
        Uses Windows API to check RAM
        """
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong

        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ("dwLength", c_ulong),
                ("dwMemoryLoad", c_ulong),
                ("dwTotalPhys", c_ulong),
                ("dwAvailPhys", c_ulong),
                ("dwTotalPageFile", c_ulong),
                ("dwAvailPageFile", c_ulong),
                ("dwTotalVirtual", c_ulong),
                ("dwAvailVirtual", c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))

        return int(memoryStatus.dwTotalPhys / 1024 ** 2) 
开发者ID:mbusb,项目名称:multibootusb,代码行数:26,代码来源:gen.py

示例2: _is_gui_available

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:23,代码来源:support.py

示例3: test_union_with_struct_packed

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def test_union_with_struct_packed(self):
        class Struct(ctypes.Structure):
            _pack_ = 1
            _fields_ = [
                ('one', ctypes.c_uint8),
                ('two', ctypes.c_uint32)
            ]

        class Union(ctypes.Union):
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint32),
                ('d', Struct),
            ]
        expected = np.dtype(dict(
            names=['a', 'b', 'c', 'd'],
            formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
            offsets=[0, 0, 0, 0],
            itemsize=ctypes.sizeof(Union)
        ))
        self.check(Union, expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:24,代码来源:test_dtype.py

示例4: test_union_packed

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def test_union_packed(self):
        class Struct(ctypes.Structure):
            _fields_ = [
                ('one', ctypes.c_uint8),
                ('two', ctypes.c_uint32)
            ]
            _pack_ = 1
        class Union(ctypes.Union):
            _pack_ = 1
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint32),
                ('d', Struct),
            ]
        expected = np.dtype(dict(
            names=['a', 'b', 'c', 'd'],
            formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
            offsets=[0, 0, 0, 0],
            itemsize=ctypes.sizeof(Union)
        ))
        self.check(Union, expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:24,代码来源:test_dtype.py

示例5: MessageClass

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def MessageClass(length=DMX_LENGTH):
    assert 0 <= length <= DMX_LENGTH
    assert length % 2 == 0, 'artnet only takes messages of even length'

    Char, Int8, Int16 = ctypes.c_char, ctypes.c_ubyte, ctypes.c_ushort

    class DMXMessage(ctypes.Structure):
        # http://artisticlicence.com/WebSiteMaster/User%20Guides/art-net.pdf p47
        _fields_ = [
            ('id', Char * 8),
            ('opCode', Int16),
            ('protVerHi', Int8),
            ('protVerLo', Int8),
            ('sequence', Int8),
            ('physical', Int8),
            ('subUni', Int8),
            ('net', Int8),
            ('lengthHi', Int8),
            ('length', Int8),
            ('data', Int8 * length),  # At position 18
        ]

    return DMXMessage 
开发者ID:ManiacalLabs,项目名称:BiblioPixel,代码行数:25,代码来源:artnet_message.py

示例6: __init__

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def __init__(self, **kwargs):
        """
        Ctypes.Structure with integrated default values.
        https://stackoverflow.com/questions/7946519/default-values-in-a-ctypes-structure/25892189#25892189

        :param kwargs: values different to defaults
        :type kwargs: dict
        """

        # sanity checks
        defaults = type(self)._defaults_
        assert type(defaults) is types.DictionaryType

        # use defaults, but override with keyword arguments, if any
        values = defaults.copy()
        for (key, val) in kwargs.items():
            values[key] = val

        # appropriately initialize ctypes.Structure
        #super().__init__(**values)                     # Python 3 syntax
        return Structure.__init__(self, **values)       # Python 2 syntax

    # http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str/1827666#1827666
    # https://wiki.python.org/moin/ctypes 
开发者ID:daq-tools,项目名称:kotori,代码行数:26,代码来源:backend_ctypes.py

示例7: create_remote_array

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def create_remote_array(subtype, len):

    class RemoteArray(_ctypes.Array):
        _length_ = len
        _type_ = subtype

        def __init__(self, addr, target):
            self._base_addr = addr
            self.target = target

        def __getitem__(self, slice):
            if not isinstance(slice, (int, long)):
                raise NotImplementedError("RemoteArray slice __getitem__")
            if slice >= len:
                raise IndexError("Access to {0} for a RemoteArray of size {1}".format(slice, len))
            item_addr = self._base_addr + (ctypes.sizeof(subtype) * slice)

            # TODO: do better ?
            class TST(ctypes.Structure):
                _fields_ = [("TST", subtype)]
            return RemoteStructure.from_structure(TST)(item_addr, target=self.target).TST
    return RemoteArray


# 64bits pointers 
开发者ID:sogeti-esec-lab,项目名称:LKD,代码行数:27,代码来源:remotectypes.py

示例8: _handle_field_getattr

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def _handle_field_getattr(self, ftype, fosset, fsize):
        s = self._target.read_memory(self._base_addr + fosset, fsize)
        if ftype in self._field_type_to_remote_type:
            return self._field_type_to_remote_type[ftype].from_buffer_with_target(bytearray(s), target=self._target).value
        if issubclass(ftype, _ctypes._Pointer):  # Pointer
            return RemoteStructurePointer.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemotePtr64):  # Pointer to remote64 bits process
            return RemoteStructurePointer64.from_buffer_with_target_and_ptr_type(bytearray(s), target=self._target, ptr_type=ftype)
        if issubclass(ftype, RemoteStructureUnion):  # Structure|Union already transfomed in remote
            return ftype(self._base_addr + fosset, self._target)
        if issubclass(ftype, ctypes.Structure):  # Structure that must be transfomed
            return RemoteStructure.from_structure(ftype)(self._base_addr + fosset, self._target)
        if issubclass(ftype, ctypes.Union):  # Union that must be transfomed
            return RemoteUnion.from_structure(ftype)(self._base_addr + fosset, self._target)
        if issubclass(ftype, _ctypes.Array):  # Arrays
            return create_remote_array(ftype._type_, ftype._length_)(self._base_addr + fosset, self._target)
        # Normal types
        # Follow the ctypes usage: if it's not directly inherited from _SimpleCData
        # We do not apply the .value
        # Seems weird but it's mandatory AND useful :D (in pe_parse)
        if _SimpleCData not in ftype.__bases__:
            return ftype.from_buffer(bytearray(s))
        return ftype.from_buffer(bytearray(s)).value 
开发者ID:sogeti-esec-lab,项目名称:LKD,代码行数:25,代码来源:remotectypes.py

示例9: write_virtual_memory

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def write_virtual_memory(self, addr, data):
        """Write data to a given virtual address

           :param addr: The Symbol to write to
           :type addr: Symbol
           :param size: The Data to write
           :type size: str or ctypes.Structure
           :returns: the size written -- :class:`int`
        """
        try:
            # ctypes structure
            size = ctypes.sizeof(data)
            buffer = ctypes.byref(data)
        except TypeError:
            # buffer
            size = len(data)
            buffer = data
        written = ULONG(0)
        addr = self.resolve_symbol(addr)
        self.DebugDataSpaces.WriteVirtual(c_uint64(addr), buffer, size, byref(written))
        return written.value 
开发者ID:sogeti-esec-lab,项目名称:LKD,代码行数:23,代码来源:dbginterface.py

示例10: write_physical_memory

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def write_physical_memory(self, addr, data):
        """Write data to a given physical address

           :param addr: The Symbol to write to
           :type addr: Symbol
           :param size: The Data to write
           :type size: str or ctypes.Structure
           :returns: the size written -- :class:`int`
        """
        try:
            # ctypes structure
            size = ctypes.sizeof(data)
            buffer = ctypes.byref(data)
        except TypeError:
            # buffer
            size = len(data)
            buffer = data
        written = ULONG(0)
        self.DebugDataSpaces.WritePhysical(c_uint64(addr), buffer, size, byref(written))
        return written.value 
开发者ID:sogeti-esec-lab,项目名称:LKD,代码行数:22,代码来源:dbginterface.py

示例11: create_vtable

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def create_vtable(cls, **implem_overwrite):
        vtables_names = [x[0] for x in cls._funcs_]
        non_expected_args = [func_name for func_name in implem_overwrite if func_name not in vtables_names]
        if non_expected_args:
            raise ValueError("Non expected function : {0}".format(non_expected_args))

        implems = []
        for name, types, func_implem in cls._funcs_:
            func_implem = implem_overwrite.get(name, func_implem)
            if func_implem is None:
                raise ValueError("Missing implementation for function <{0}>".format(name))
            implems.append(create_c_callable(func_implem, types))

        class Vtable(ctypes.Structure):
            _fields_ = [(name, ctypes.c_void_p) for name in vtables_names]

        return Vtable(*implems) 
开发者ID:sogeti-esec-lab,项目名称:LKD,代码行数:19,代码来源:simple_com.py

示例12: compile

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def compile(self, structure):
        source = self.gen_struct_class(structure)
        c = compile(source, '<compiled>', 'exec')

        env = {
            'OrderedDict': OrderedDict,
            'Structure': Structure,
            'Instance': Instance,
            'Expression': Expression,
            'EnumInstance': EnumInstance,
            'PointerInstance': PointerInstance,
            'BytesInteger': BytesInteger,
            'BitBuffer': BitBuffer,
            'struct': struct,
            'xrange': xrange,
        }

        exec(c, env)
        sc = env[structure.name](self.cstruct, structure, source)

        return sc 
开发者ID:fox-it,项目名称:dissect.cstruct,代码行数:23,代码来源:cstruct.py

示例13: __init__

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def __init__(self, this):
        if not this:
            raise WindowsError('Could not construct {}'.format(self.__class__))
        self.this = ctypes.cast(this, ctypes.POINTER(self.__class__))
        ctypes.Structure.__init__(self) 
开发者ID:fireeye,项目名称:cWMI,代码行数:7,代码来源:com.py

示例14: getWindowsBuild

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def getWindowsBuild():   
    class OSVersionInfo(ctypes.Structure):
        _fields_ = [
            ("dwOSVersionInfoSize" , ctypes.c_int),
            ("dwMajorVersion"      , ctypes.c_int),
            ("dwMinorVersion"      , ctypes.c_int),
            ("dwBuildNumber"       , ctypes.c_int),
            ("dwPlatformId"        , ctypes.c_int),
            ("szCSDVersion"        , ctypes.c_char*128)];
    GetVersionEx = getattr( ctypes.windll.kernel32 , "GetVersionExA")
    version  = OSVersionInfo()
    version.dwOSVersionInfoSize = ctypes.sizeof(OSVersionInfo)
    GetVersionEx( ctypes.byref(version) )    
    return version.dwBuildNumber 
开发者ID:skelsec,项目名称:minidump,代码行数:16,代码来源:createminidump.py

示例15: as_ctypes_type

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import Structure [as 别名]
def as_ctypes_type(dtype):
        """
        Convert a dtype into a ctypes type.

        Parameters
        ----------
        dtype : dtype
            The dtype to convert

        Returns
        -------
        ctypes
            A ctype scalar, union, array, or struct

        Raises
        ------
        NotImplementedError
            If the conversion is not possible

        Notes
        -----
        This function does not losslessly round-trip in either direction.

        ``np.dtype(as_ctypes_type(dt))`` will:
         - insert padding fields
         - reorder fields to be sorted by offset
         - discard field titles

        ``as_ctypes_type(np.dtype(ctype))`` will:
         - discard the class names of ``Structure``s and ``Union``s
         - convert single-element ``Union``s into single-element ``Structure``s
         - insert padding fields

        """
        return _ctype_from_dtype(_dtype(dtype)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:37,代码来源:ctypeslib.py


注:本文中的ctypes.Structure方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。