我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.c_ushort()。
def win_create_mdb(mdb_path, sort_order = "General\0\0"): if sys.platform not in ('win32','cli'): raise Exception('This function is available for use in Windows only.') mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d] if mdb_driver == []: raise Exception('Access Driver is not found.') else: driver_name = mdb_driver[0].encode('mbcs') #CREATE_DB=<path name> <sort order> ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p] if py_v3: c_Path = bytes("CREATE_DB=" + mdb_path + " " + sort_order,'mbcs') else: c_Path = "CREATE_DB=" + mdb_path + " " + sort_order ODBC_ADD_SYS_DSN = 1 ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path) if not ret: raise Exception('Failed to create Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %mdb_path)
def win_compact_mdb(mdb_path, compacted_mdb_path, sort_order = "General\0\0"): if sys.platform not in ('win32','cli'): raise Exception('This function is available for use in Windows only.') mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d] if mdb_driver == []: raise Exception('Access Driver is not found.') else: driver_name = mdb_driver[0].encode('mbcs') #COMPACT_DB=<source path> <destination path> <sort order> ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p] #driver_name = "Microsoft Access Driver (*.mdb)" if py_v3: c_Path = bytes("COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order,'mbcs') #driver_name = bytes(driver_name,'mbcs') else: c_Path = "COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order ODBC_ADD_SYS_DSN = 1 ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path) if not ret: raise Exception('Failed to compact Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %compacted_mdb_path)
def wrap(self, gammaramp): ''' Wraps a nested python sequence. ''' red, green, blue = gammaramp size = min(len(red), len(green), len(blue)) array_type = ctypes.c_ushort*size self.size = ctypes.c_uint(size) self.red_array = array_type() self.green_array = array_type() self.blue_array = array_type() for i in range(self.size): self.red_array[i] = int(red[i]*65535) self.green_array[i] = int(green[i]*65535) self.blue_array[i] = int(blue[i]*65535) pointer_type = ctypes.POINTER(ctypes.c_ushort) self.red = ctypes.cast(self.red_array, pointer_type) self.green = ctypes.cast(self.green_array, pointer_type) self.blue = ctypes.cast(self.blue_array, pointer_type)
def win32_version(): import ctypes class OSVERSIONINFOEXW(ctypes.Structure): _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong), ('dwMajorVersion', ctypes.c_ulong), ('dwMinorVersion', ctypes.c_ulong), ('dwBuildNumber', ctypes.c_ulong), ('dwPlatformId', ctypes.c_ulong), ('szCSDVersion', ctypes.c_wchar*128), ('wServicePackMajor', ctypes.c_ushort), ('wServicePackMinor', ctypes.c_ushort), ('wSuiteMask', ctypes.c_ushort), ('wProductType', ctypes.c_byte), ('wReserved', ctypes.c_byte)] """ Get's the OS major and minor versions. Returns a tuple of (OS_MAJOR, OS_MINOR). """ os_version = OSVERSIONINFOEXW() os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version) retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version)) if retcode != 0: raise Exception("Failed to get OS version") return os_version.dwMajorVersion
def rename_regkey(skey, ssubkey, dsubkey): """Rename an entire tree of values in the registry. Function by Thorsten Sick.""" res_handle = HANDLE() options = DWORD(0) res = RegOpenKeyExW( skey, ssubkey, options, _winreg.KEY_ALL_ACCESS, byref(res_handle) ) if not res: bsize = c_ushort(len(dsubkey) * 2) us = UNICODE_STRING() us.Buffer = c_wchar_p(dsubkey) us.Length = bsize us.MaximumLength = bsize res = NtRenameKey(res_handle, pointer(us)) if res: log.warning("Error renaming %s\\%s to %s (0x%x)", skey, ssubkey, dsubkey, res % 2**32) if res_handle: RegCloseKey(res_handle)
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)
def win32_version_string(): import ctypes class OSVERSIONINFOEXW(ctypes.Structure): _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong), ('dwMajorVersion', ctypes.c_ulong), ('dwMinorVersion', ctypes.c_ulong), ('dwBuildNumber', ctypes.c_ulong), ('dwPlatformId', ctypes.c_ulong), ('szCSDVersion', ctypes.c_wchar*128), ('wServicePackMajor', ctypes.c_ushort), ('wServicePackMinor', ctypes.c_ushort), ('wSuiteMask', ctypes.c_ushort), ('wProductType', ctypes.c_byte), ('wReserved', ctypes.c_byte)] """ Get's the OS major and minor versions. Returns a tuple of (OS_MAJOR, OS_MINOR). """ os_version = OSVERSIONINFOEXW() os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version) retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version)) if retcode != 0: raise Exception("Failed to get OS version") version_string = "Version:%d-%d; Build:%d; Platform:%d; CSD:%s; ServicePack:%d-%d; Suite:%d; ProductType:%d" % ( os_version.dwMajorVersion, os_version.dwMinorVersion, os_version.dwBuildNumber, os_version.dwPlatformId, os_version.szCSDVersion, os_version.wServicePackMajor, os_version.wServicePackMinor, os_version.wSuiteMask, os_version.wReserved ) return version_string
def AwaClientSession_SetIPCAsUDP(self, session, address, port): self._lib.AwaClientSession_SetIPCAsUDP.restype = c_int self._lib.AwaClientSession_SetIPCAsUDP.argtypes = [c_void_p, c_char_p, c_ushort] return self._lib.AwaClientSession_SetIPCAsUDP(session, address, port)
def AwaServerSession_SetIPCAsUDP(self, session, address, port): self._lib.AwaClientSession_SetIPCAsUDP.restype = c_int self._lib.AwaClientSession_SetIPCAsUDP.argtypes = [c_void_p, c_char_p, c_ushort] return self._lib.AwaServerSession_SetIPCAsUDP(session, address, port)
def GetVersion(self): version = C.c_ushort() self._GetVersion(self.handle, C.byref(version)) # int * return version.value
def attach_filter(fd, iface, bpf_filter_string): # GV: move to a method of _L2bpfSocket """Attach a BPF filter to the BPF file descriptor""" # Retrieve the BPF byte code in decimal command = "%s -i %s -ddd -s 1600 '%s'" % (conf.prog.tcpdump, iface, bpf_filter_string) try: f = os.popen(command) except OSError, msg: raise Scapy_Exception("Failed to execute tcpdump: (%s)" % msg) # Convert the byte code to a BPF program structure lines = f.readlines() if lines == []: raise Scapy_Exception("Got an empty BPF filter from tcpdump !") # Allocate BPF instructions size = int(lines[0]) bpf_insn_a = bpf_insn * size bip = bpf_insn_a() # Fill the BPF instruction structures with the byte code lines = lines[1:] for i in xrange(len(lines)): values = [int(v) for v in lines[i].split()] bip[i].code = c_ushort(values[0]) bip[i].jt = c_ubyte(values[1]) bip[i].j = c_ubyte(values[2]) bip[i].k = c_uint(values[3]) # Create the BPF program and assign it to the interface bp = bpf_program(size, bip) ret = LIBC.ioctl(c_int(fd), BIOCSETF, cast(pointer(bp), c_char_p)) if ret < 0: raise Scapy_Exception("Can't attach the BPF filter !") # Interface manipulation functions
def __exma_bindRendezvous(self, outputs, namespaceUri, schemaVersion): """bindRendezvous taken from exma.dll""" rendezvous = ctypes.c_ushort() sock = ctypes.c_uint() ret = exma.bindRendezvous(ctypes.pointer(rendezvous), ctypes.pointer(sock)) return (rendezvous.value, sock.value)
def doRendezvousServer(self, rendezvous, sock): """Setup the rendezvous server so the next plugin can talk 'through' us""" if sock is not None: r = ctypes.c_uint(sock) if -1 == exma.sendSockets(r): return -1 exma.closeRendezvous( ctypes.c_ushort(rendezvous), r) sock = None return 0 # # These need to be implemented by the exploit #
def init_crc16(self): """The algorithm uses tables with precalculated values""" for i in range(0, 256): crc = c_ushort(i).value for j in range(0, 8): if crc & 0x0001: crc = c_ushort(crc >> 1).value ^ self.crc16_constant else: crc = c_ushort(crc >> 1).value self.crc16_tab.append(crc)
def _getitem(self, start, end): if self.itemsize == 1: # byte-wise access return self.source[start:end] # move the pointer to the correct location src = ctypes.byref(self.source.contents, start) casttype = ctypes.c_ubyte if self.itemsize == 2: casttype = ctypes.c_ushort elif self.itemsize == 3: # TODO raise NotImplementedError("unsupported bpp") elif self.itemsize == 4: casttype = ctypes.c_uint return ctypes.cast(src, ctypes.POINTER(casttype)).contents.value
def _setitem(self, start, end, value): target = None if self.itemsize == 1: target = ctypes.cast(self.source, ctypes.POINTER(ctypes.c_ubyte)) elif self.itemsize == 2: target = ctypes.cast(self.source, ctypes.POINTER(ctypes.c_ushort)) elif self.itemsize == 3: # TODO raise NotImplementedError("unsupported bpp") elif self.itemsize == 4: target = ctypes.cast(self.source, ctypes.POINTER(ctypes.c_uint)) value = prepare_color(value, self._surface) target[start // self.itemsize] = value
def test_to_ctypes(self): for seq, dtype in ((singlebyteseq, ctypes.c_ubyte), (singlebytebuf, ctypes.c_ubyte), (doublebyteseq, ctypes.c_ushort), (doublebytebuf, ctypes.c_ushort), (quadbyteseq, ctypes.c_uint), (quadbytebuf, ctypes.c_uint)): bytebuf, size = sdlextarray.to_ctypes(seq, dtype) self.assertEqual(size, len(seq)) for index, x in enumerate(bytebuf): self.assertEqual(x, seq[index])
def prepare(self, query_string): """prepare a query""" #self._free_results(FREE_STATEMENT) if not self.connection: self.close() if type(query_string) == unicode: c_query_string = wchar_pointer(UCS_buf(query_string)) ret = ODBC_API.SQLPrepareW(self.stmt_h, c_query_string, len(query_string)) else: c_query_string = ctypes.c_char_p(query_string) ret = ODBC_API.SQLPrepare(self.stmt_h, c_query_string, len(query_string)) if ret != SQL_SUCCESS: check_success(self, ret) self._PARAM_SQL_TYPE_LIST = [] if self.connection.support_SQLDescribeParam: # SQLServer's SQLDescribeParam only supports DML SQL, so avoid the SELECT statement if True:# 'SELECT' not in query_string.upper(): #self._free_results(NO_FREE_STATEMENT) NumParams = c_short() ret = ODBC_API.SQLNumParams(self.stmt_h, ADDR(NumParams)) if ret != SQL_SUCCESS: check_success(self, ret) for col_num in range(NumParams.value): ParameterNumber = ctypes.c_ushort(col_num + 1) DataType = c_short() ParameterSize = ctypes.c_size_t() DecimalDigits = c_short() Nullable = c_short() ret = ODBC_API.SQLDescribeParam( self.stmt_h, ParameterNumber, ADDR(DataType), ADDR(ParameterSize), ADDR(DecimalDigits), ADDR(Nullable), ) if ret != SQL_SUCCESS: try: check_success(self, ret) except DatabaseError: if sys.exc_info()[1].value[0] == '07009': self._PARAM_SQL_TYPE_LIST = [] break else: raise sys.exc_info()[1] except: raise sys.exc_info()[1] self._PARAM_SQL_TYPE_LIST.append((DataType.value,DecimalDigits.value)) self.statement = query_string