本文整理汇总了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)
示例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)
示例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)
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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)
示例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
示例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)
示例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
示例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))