Python ctypes.sizeof() Examples
The following are 30
code examples of ctypes.sizeof().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ctypes
, or try the search function
.
Example #1
Source File: gen.py From multibootusb with GNU General Public License v2.0 | 12 votes |
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)
Example #2
Source File: test_dtype.py From recruit with Apache License 2.0 | 8 votes |
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)
Example #3
Source File: winapi.py From sublime3dsmax with MIT License | 6 votes |
def GetClassNameA(hWnd): _GetClassNameA = windll.user32.GetClassNameA _GetClassNameA.argtypes = [HWND, LPSTR, ctypes.c_int] _GetClassNameA.restype = ctypes.c_int nMaxCount = 0x1000 dwCharSize = sizeof(CHAR) while 1: lpClassName = ctypes.create_string_buffer(nMaxCount) nCount = _GetClassNameA(hWnd, lpClassName, nMaxCount) if nCount == 0: raise ctypes.WinError() if nCount < nMaxCount - dwCharSize: break nMaxCount += 0x1000 return str(lpClassName.value)
Example #4
Source File: _ffi.py From oscrypto with MIT License | 6 votes |
def array_from_pointer(library, name, point, size): ffi_obj = _get_ffi(library) array = ffi_obj.cast('%s[%s]' % (name, size), point) total_bytes = ffi_obj.sizeof(array) if total_bytes == 0: return [] output = [] string_types = { 'LPSTR': True, 'LPCSTR': True, 'LPWSTR': True, 'LPCWSTR': True, 'char *': True, 'wchar_t *': True, } string_type = name in string_types for i in range(0, size): value = array[i] if string_type: value = ffi_obj.string(value) output.append(value) return output
Example #5
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_DriverName(self, channel): """Get device driver name Retrieves the name of the device driver (e.g. "kcany") for the device connected to channel. The device driver names have no special meanings and may change from a release to another. Args: channel (int): The channel you are interested in Returns: name (str): The device driver name """ self.fn = inspect.currentframe().f_code.co_name name = ct.create_string_buffer(80) self.dll.canGetChannelData(channel, canCHANNELDATA_DRIVER_NAME, ct.byref(name), ct.sizeof(name)) return name.value
Example #6
Source File: support.py From jawfish with MIT License | 6 votes |
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)
Example #7
Source File: ctypes_qsort.py From Expert-Python-Programming_Second-Edition with BSD 3-Clause "New" or "Revised" License | 6 votes |
def main(): numbers = list(range(5)) shuffle(numbers) print("shuffled: ", numbers) # create new type representing array with lenght # same as the lenght of numbers list NumbersArray = ctypes.c_int * len(numbers) # create new C array using a new type c_array = NumbersArray(*numbers) libc.qsort( # pointer to the sorted array c_array, # length of the array len(c_array), # size of single array element ctypes.sizeof(ctypes.c_int), # callback (pointer to the C comparison function) CMPFUNC(ctypes_int_compare) ) print("sorted: ", list(c_array))
Example #8
Source File: support.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
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)
Example #9
Source File: test_ctypeslib.py From recruit with Apache License 2.0 | 6 votes |
def test_padded_union(self): dt = np.dtype(dict( names=['a', 'b'], offsets=[0, 0], formats=[np.uint16, np.uint32], itemsize=5, )) ct = np.ctypeslib.as_ctypes_type(dt) assert_(issubclass(ct, ctypes.Union)) assert_equal(ctypes.sizeof(ct), dt.itemsize) assert_equal(ct._fields_, [ ('a', ctypes.c_uint16), ('b', ctypes.c_uint32), ('', ctypes.c_char * 5), # padding ])
Example #10
Source File: libbytesize_unittest.py From libbytesize with GNU Lesser General Public License v2.1 | 6 votes |
def testDivInt(self): x = SizeStruct.new_from_str("1 MiB") y = 1024 divResult = x.div_int(y).get_bytes() self.assertEqual(divResult, (1024, 1)) x = SizeStruct.new_from_str("-1 MiB") y = 1077 divResult = x.div_int(y).get_bytes() self.assertEqual(divResult, (973, -1)) try: x = SizeStruct.new_from_bytes(2 * 2**36, 1) y = 2**36 res = x.div_int(y).get_bytes() self.assertEqual(res, (2, 1)) except OverflowError: # ULONG_MAX is the real limit for division, if it's smaller than # UINT64_MAX, an error is expected, otherwise it is a bug if ctypes.sizeof(ctypes.c_ulong) == 4: pass #enddef
Example #11
Source File: createminidump.py From minidump with MIT License | 6 votes |
def enum_pids(): max_array = c_ulong * 4096 # define long array to capture all the processes pProcessIds = max_array() # array to store the list of processes pBytesReturned = c_ulong() # the number of bytes returned in the array #EnumProcess res = EnumProcesses( ctypes.byref(pProcessIds), ctypes.sizeof(pProcessIds), ctypes.byref(pBytesReturned) ) if res == 0: logging.error(WinError(get_last_error())) return [] # get the number of returned processes nReturned = int(pBytesReturned.value/ctypes.sizeof(c_ulong())) return [i for i in pProcessIds[:nReturned]] #https://msdn.microsoft.com/en-us/library/windows/desktop/ms683217(v=vs.85).aspx
Example #12
Source File: util.py From ai-platform with MIT License | 6 votes |
def get_dtype_and_ctype(type_obj: Any) -> Tuple[np.dtype, Any]: """Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes.""" type_str = None if isinstance(type_obj, str): type_str = type_obj elif hasattr(type_obj, "__name__"): type_str = type_obj.__name__ elif hasattr(type_obj, "name"): type_str = type_obj.name else: raise RuntimeError("Cannot infer type name from input") assert type_str in _str_to_ctype.keys() my_dtype = np.dtype(type_str) my_ctype = _str_to_ctype[type_str] assert my_dtype.itemsize == ctypes.sizeof(my_ctype) return my_dtype, my_ctype
Example #13
Source File: privileges.py From minidump with MIT License | 6 votes |
def enable_debug_privilege(): """ Try to assign the symlink privilege to the current process token. Return True if the assignment is successful. """ # create a space in memory for a TOKEN_PRIVILEGES structure # with one element size = ctypes.sizeof(TOKEN_PRIVILEGES) size += ctypes.sizeof(LUID_AND_ATTRIBUTES) buffer = ctypes.create_string_buffer(size) tp = ctypes.cast(buffer, ctypes.POINTER(TOKEN_PRIVILEGES)).contents tp.count = 1 tp.get_array()[0].enable() tp.get_array()[0].LUID = get_debug_luid() token = get_process_token() res = AdjustTokenPrivileges(token, False, tp, 0, None, None) if res == 0: raise RuntimeError("Error in AdjustTokenPrivileges") ERROR_NOT_ALL_ASSIGNED = 1300 return ctypes.windll.kernel32.GetLastError() != ERROR_NOT_ALL_ASSIGNED
Example #14
Source File: test_dtype.py From recruit with Apache License 2.0 | 6 votes |
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)
Example #15
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_EAN(self, channel): """Get EAN code Retrieves the EAN number for the device connected to channel. If there is no EAN number, "00-00000-00000-0" will be returned. Args: channel (int): The channel you are interested in Returns: ean (str): The device's EAN number """ self.fn = inspect.currentframe().f_code.co_name buf_type = ct.c_ulong * 2 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CARD_UPC_NO, ct.byref(buf), ct.sizeof(buf)) (ean_lo, ean_hi) = struct.unpack('LL', buf) return "%02x-%05x-%05x-%x" % (ean_hi >> 12, ((ean_hi & 0xfff) << 8) | (ean_lo >> 24), (ean_lo >> 4) & 0xfffff, ean_lo & 0xf)
Example #16
Source File: winapi.py From sublime3dsmax with MIT License | 6 votes |
def GetClassNameW(hWnd): _GetClassNameW = windll.user32.GetClassNameW _GetClassNameW.argtypes = [HWND, LPWSTR, ctypes.c_int] _GetClassNameW.restype = ctypes.c_int nMaxCount = 0x1000 dwCharSize = sizeof(WCHAR) while 1: lpClassName = ctypes.create_unicode_buffer(nMaxCount) nCount = _GetClassNameW(hWnd, lpClassName, nMaxCount) if nCount == 0: raise ctypes.WinError() if nCount < nMaxCount - dwCharSize: break nMaxCount += 0x1000 return str(lpClassName.value)
Example #17
Source File: pdraw.py From olympe with BSD 3-Clause "New" or "Revised" License | 6 votes |
def info(self): """ Returns a dictionary of video frame info """ if self._frame_info is not None: return self._frame_info frame = self._get_pdraw_video_frame() if not frame: return self._frame_info # convert the binary metadata into json self._frame_info = {} jsonbuf = ctypes.create_string_buffer(4096) res = od.pdraw_video_frame_to_json_str( frame, jsonbuf, ctypes.sizeof(jsonbuf)) if res < 0: self.logger.error( 'pdraw_frame_metadata_to_json returned error {}'.format(res)) else: self._frame_info = json.loads(str(jsonbuf.value, encoding="utf-8")) return self._frame_info
Example #18
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_Serial(self, channel): """Get device serial number Retrieves the serial number for the device connected to channel. If the device does not have a serial number, 0 is returned. Args: channel (int): The channel you are interested in Returns: serial (int): The device serial number """ self.fn = inspect.currentframe().f_code.co_name buf_type = ct.c_ulong * 2 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CARD_SERIAL_NO, ct.byref(buf), ct.sizeof(buf)) (serial_lo, serial_hi) = struct.unpack('LL', buf) # serial_hi is always 0 return serial_lo
Example #19
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_Name(self, channel): """Get the product name. Retrieves the product name of the device connected to channel. The name is returned as an ASCII string. Args: channel (int): The channel you are interested in Returns: name (string): The product name """ self.fn = inspect.currentframe().f_code.co_name name = ct.create_string_buffer(80) self.dll.canGetChannelData(channel, canCHANNELDATA_DEVDESCR_ASCII, ct.byref(name), ct.sizeof(name)) buf_type = ct.c_uint * 1 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CHAN_NO_ON_CARD, ct.byref(buf), ct.sizeof(buf)) return "%s (channel %d)" % (name.value, buf[0])
Example #20
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_Chan_No_On_Card(self, channel): """Get the channel number on the card. Retrieves the channel number, as numbered locally on the card, device connected to channel. Args: channel (int): The channel you are interested in Returns: number (int): The local channel number """ self.fn = inspect.currentframe().f_code.co_name number = ct.c_ulong() self.dll.canGetChannelData(channel, canCHANNELDATA_CHAN_NO_ON_CARD, ct.byref(number), ct.sizeof(number)) buf_type = ct.c_uint * 1 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CHAN_NO_ON_CARD, ct.byref(buf), ct.sizeof(buf)) return number.value
Example #21
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_CardNumber(self, channel): """Get the card number Retrieves the card's number in the computer. Each card type is numbered separately. For example, the first PCIEcan card in a machine will have number 0, the second PCIEcan number 1, etc. Args: channel (int): The channel you are interested in Returns: card_number (int): The device's card number """ self.fn = inspect.currentframe().f_code.co_name buf_type = ct.c_ulong buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CARD_NUMBER, ct.byref(buf), ct.sizeof(buf)) return buf.value
Example #22
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_EAN(self, channel): """Get EAN code Retrieves the EAN number for the device connected to channel. If there is no EAN number, "00-00000-00000-0" will be returned. Args: channel (int): The channel you are interested in Returns: ean (str): The device's EAN number """ self.fn = inspect.currentframe().f_code.co_name buf_type = ct.c_ulong * 2 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CARD_UPC_NO, ct.byref(buf), ct.sizeof(buf)) (ean_lo, ean_hi) = struct.unpack('LL', buf) return "%02x-%05x-%05x-%x" % (ean_hi >> 12, ((ean_hi & 0xfff) << 8) | (ean_lo >> 24), (ean_lo >> 4) & 0xfffff, ean_lo & 0xf)
Example #23
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_Serial(self, channel): """Get device serial number Retrieves the serial number for the device connected to channel. If the device does not have a serial number, 0 is returned. Args: channel (int): The channel you are interested in Returns: serial (int): The device serial number """ self.fn = inspect.currentframe().f_code.co_name buf_type = ct.c_ulong * 2 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CARD_SERIAL_NO, ct.byref(buf), ct.sizeof(buf)) (serial_lo, serial_hi) = struct.unpack('LL', buf) # serial_hi is always 0 return serial_lo
Example #24
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_DriverName(self, channel): """Get device driver name Retrieves the name of the device driver (e.g. "kcany") for the device connected to channel. The device driver names have no special meanings and may change from a release to another. Args: channel (int): The channel you are interested in Returns: name (str): The device driver name """ self.fn = inspect.currentframe().f_code.co_name name = ct.create_string_buffer(80) self.dll.canGetChannelData(channel, canCHANNELDATA_DRIVER_NAME, ct.byref(name), ct.sizeof(name)) return name.value
Example #25
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_Firmware(self, channel): """Get device firmware version Retrieves the firmvare version numbers for the device connected to channel. Args: channel (int): The channel you are interested in Returns: major (int): The major version number minor (int): The minor version number build (int): The build number """ self.fn = inspect.currentframe().f_code.co_name buf_type = ct.c_ushort * 4 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CARD_FIRMWARE_REV, ct.byref(buf), ct.sizeof(buf)) (build, release, minor, major) = struct.unpack('HHHH', buf) return (major, minor, build)
Example #26
Source File: winapi.py From sublime3dsmax with MIT License | 6 votes |
def GetWindowTextW(hWnd): _GetWindowTextW = windll.user32.GetWindowTextW _GetWindowTextW.argtypes = [HWND, LPWSTR, ctypes.c_int] _GetWindowTextW.restype = ctypes.c_int nMaxCount = 0x1000 dwCharSize = sizeof(CHAR) while 1: lpString = ctypes.create_string_buffer(nMaxCount) nCount = _GetWindowTextW(hWnd, lpString, nMaxCount) if nCount == 0: raise ctypes.WinError() if nCount < nMaxCount - dwCharSize: break nMaxCount += 0x1000 return str(lpString.value)
Example #27
Source File: winapi.py From sublime3dsmax with MIT License | 6 votes |
def GetWindowTextA(hWnd): _GetWindowTextA = windll.user32.GetWindowTextA _GetWindowTextA.argtypes = [HWND, LPSTR, ctypes.c_int] _GetWindowTextA.restype = ctypes.c_int nMaxCount = 0x1000 dwCharSize = sizeof(CHAR) while 1: lpString = ctypes.create_string_buffer(nMaxCount) nCount = _GetWindowTextA(hWnd, lpString, nMaxCount) if nCount == 0: raise ctypes.WinError() if nCount < nMaxCount - dwCharSize: break nMaxCount += 0x1000 return str(lpString.value)
Example #28
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_CardNumber(self, channel): """Get the card number Retrieves the card's number in the computer. Each card type is numbered separately. For example, the first PCIEcan card in a machine will have number 0, the second PCIEcan number 1, etc. Args: channel (int): The channel you are interested in Returns: card_number (int): The device's card number """ self.fn = inspect.currentframe().f_code.co_name buf_type = ct.c_ulong buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CARD_NUMBER, ct.byref(buf), ct.sizeof(buf)) return buf.value
Example #29
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_Name(self, channel): """Get the product name. Retrieves the product name of the device connected to channel. The name is returned as an ASCII string. Args: channel (int): The channel you are interested in Returns: name (string): The product name """ self.fn = inspect.currentframe().f_code.co_name name = ct.create_string_buffer(80) self.dll.canGetChannelData(channel, canCHANNELDATA_DEVDESCR_ASCII, ct.byref(name), ct.sizeof(name)) buf_type = ct.c_uint * 1 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CHAN_NO_ON_CARD, ct.byref(buf), ct.sizeof(buf)) return "%s (channel %d)" % (name.value, buf[0])
Example #30
Source File: canlib.py From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License | 6 votes |
def getChannelData_Chan_No_On_Card(self, channel): """Get the channel number on the card. Retrieves the channel number, as numbered locally on the card, device connected to channel. Args: channel (int): The channel you are interested in Returns: number (int): The local channel number """ self.fn = inspect.currentframe().f_code.co_name number = ct.c_ulong() self.dll.canGetChannelData(channel, canCHANNELDATA_CHAN_NO_ON_CARD, ct.byref(number), ct.sizeof(number)) buf_type = ct.c_uint * 1 buf = buf_type() self.dll.canGetChannelData(channel, canCHANNELDATA_CHAN_NO_ON_CARD, ct.byref(buf), ct.sizeof(buf)) return number.value