Python ctypes.create_string_buffer() Examples
The following are 30
code examples of ctypes.create_string_buffer().
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: lcs.py From BASS with GNU General Public License v2.0 | 7 votes |
def hamming_klcs(seqs): """ Implementation of k-LCS as described in Christian Blichmann's thesis "Automatisierte Signaturgenerierung fuer Malware-Staemme" on page 52. This algorithm will not forcibly find THE longest common subsequence among all sequences, as the subsequence returned by the 2-LCS algorithm might not be the optimal one from the set of longest common subsequences. :see: https://static.googleusercontent.com/media/www.zynamics.com/en//downloads/blichmann-christian--diplomarbeit--final.pdf :param seqs: List of sequences :return: A shared subsequence between the input sequences. Not necessarily the longest one, and only one of several that might exist. """ c_seqs_type = c_char_p * len(seqs) c_seqs = c_seqs_type() c_seqs[:] = seqs c_lens_type = c_size_t * len(seqs) c_lens = c_lens_type() c_lens[:] = [len(seq) for seq in seqs] result = create_string_buffer("\0" * min(len(seq) for seq in seqs)) result_len = c_size_t(len(result)) ret = _lib.hamming_klcs_c(c_seqs, c_lens, len(seqs), result, byref(result_len)) if ret == 0: return result[:result_len.value] else: raise RuntimeError("lcs returned error code %d" % ret)
Example #2
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 #3
Source File: low_level.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError("Error copying C string from CFStringRef") string = buffer.value if string is not None: string = string.decode("utf-8") return string
Example #4
Source File: lcs.py From BASS with GNU General Public License v2.0 | 6 votes |
def lcs(s, t): """ Calculate the longest common subsequence between two sequences in O(min(len(x), len(y))) space and O(len(x) * len(y)) time. Implemented in C++. Since only one instance from the set of longest common subsequences is returned, the algorithm has the unpleasing property of not being commutative (i.e., changing the input vectors changes the result). :see: https://en.wikipedia.org/wiki/Hirschberg%27s_algorithm :param x: First input sequence. :param y: Second input sequence. :return: LCS(x, y) """ result = create_string_buffer("\0" * min(len(s), len(t))) result_len = c_size_t(len(result)) if isinstance(s, list): s = "".join(s) if isinstance(t, list): t = "".join(t) ret = _lib.hirschberg_lcs(s, len(s), t, len(t), result, byref(result_len)) if ret == 0: return result[:result_len.value] else: raise RuntimeError("lcs returned error code %d" % ret)
Example #5
Source File: RATAttack.py From RAT-via-Telegram with MIT License | 6 votes |
def get_curr_window(): user32 = ctypes.windll.user32 kernel32 = ctypes.windll.kernel32 hwnd = user32.GetForegroundWindow() pid = ctypes.c_ulong(0) user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) process_id = "%d" % pid.value executable = ctypes.create_string_buffer(512) h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid) ctypes.windll.psapi.GetModuleBaseNameA(h_process, None, ctypes.byref(executable), 512) window_title = ctypes.create_string_buffer(512) length = user32.GetWindowTextA(hwnd, ctypes.byref(window_title), 512) pid_info = "\n[ PID %s - %s - %s ]" % (process_id, executable.value, window_title.value) kernel32.CloseHandle(hwnd) kernel32.CloseHandle(h_process) return pid_info
Example #6
Source File: key.py From checklocktimeverify-demos with GNU General Public License v3.0 | 6 votes |
def verify(self, hash, sig): # pylint: disable=redefined-builtin """Verify a DER signature""" if not sig: return False # New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first. norm_sig = ctypes.c_void_p(0) _ssl.d2i_ECDSA_SIG(ctypes.byref(norm_sig), ctypes.byref(ctypes.c_char_p(sig)), len(sig)) derlen = _ssl.i2d_ECDSA_SIG(norm_sig, 0) if derlen == 0: _ssl.ECDSA_SIG_free(norm_sig) return False norm_der = ctypes.create_string_buffer(derlen) _ssl.i2d_ECDSA_SIG(norm_sig, ctypes.byref(ctypes.pointer(norm_der))) _ssl.ECDSA_SIG_free(norm_sig) # -1 = error, 0 = bad sig, 1 = good return _ssl.ECDSA_verify(0, hash, len(hash), norm_der, derlen, self.k) == 1
Example #7
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 #8
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 #9
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 #10
Source File: low_level.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError("Error copying C string from CFStringRef") string = buffer.value if string is not None: string = string.decode("utf-8") return string
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: terminalsize.py From asciidots with GNU Affero General Public License v3.0 | 6 votes |
def _get_terminal_size_windows(): try: from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) sizex = right - left + 1 sizey = bottom - top + 1 return sizex, sizey except: pass
Example #16
Source File: cet.py From libcet with MIT License | 6 votes |
def process_data(self, indata, key, is_enc=True): is_enc = self.ENCRYPT if is_enc else self.DECRYPT length = len(indata) indata = ctypes.create_string_buffer(indata, length) outdata = ctypes.create_string_buffer(length) n = ctypes.c_int(0) key = DES_cblock(*tuple(key)) key_schedule = DES_key_schedule() self.libcrypto.DES_set_odd_parity(key) self.libcrypto.DES_set_key_checked( ctypes.byref(key), ctypes.byref(key_schedule)) self.libcrypto.DES_cfb64_encrypt( ctypes.byref(indata), ctypes.byref(outdata), ctypes.c_int(length), ctypes.byref(key_schedule), ctypes.byref(key), ctypes.byref(n), ctypes.c_int(is_enc)) return outdata.raw
Example #17
Source File: terminal.py From recruit with Apache License 2.0 | 6 votes |
def _get_terminal_size_windows(): try: from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) except (AttributeError, ValueError): return None if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) sizex = right - left + 1 sizey = bottom - top + 1 return sizex, sizey else: return None
Example #18
Source File: shader.py From ratcave with MIT License | 6 votes |
def _createShader(self, strings, shadertype): # create the shader handle shader = gl.glCreateShader(shadertype) # convert the source strings into a ctypes pointer-to-char array, and upload them # this is deep, dark, dangerous black magick - don't try stuff like this at home! strings = tuple(s.encode('ascii') for s in strings) # Nick added, for python3 src = (c_char_p * len(strings))(*strings) gl.glShaderSource(shader, len(strings), cast(pointer(src), POINTER(POINTER(c_char))), None) # compile the shader gl.glCompileShader(shader) # retrieve the compile status compile_success = c_int(0) gl.glGetShaderiv(shader, gl.GL_COMPILE_STATUS, byref(compile_success)) # if compilation failed, print the log if compile_success: gl.glAttachShader(self.id, shader) else: gl.glGetShaderiv(shader, gl.GL_INFO_LOG_LENGTH, byref(compile_success)) # retrieve the log length buffer = create_string_buffer(compile_success.value) # create a buffer for the log gl.glGetShaderInfoLog(shader, compile_success, None, buffer) # retrieve the log text print(buffer.value) # print the log to the console
Example #19
Source File: shader.py From ratcave with MIT License | 6 votes |
def link(self): """link the program, making it the active shader. .. note:: Shader.bind() is preferred here, because link() Requires the Shader to be compiled already. """ gl.glLinkProgram(self.id) # Check if linking was successful. If not, print the log. link_status = c_int(0) gl.glGetProgramiv(self.id, gl.GL_LINK_STATUS, byref(link_status)) if not link_status: gl.glGetProgramiv(self.id, gl.GL_INFO_LOG_LENGTH, byref(link_status)) # retrieve the log length buffer = create_string_buffer(link_status.value) # create a buffer for the log gl.glGetProgramInfoLog(self.id, link_status, None, buffer) # retrieve the log text print(buffer.value) # print the log to the console self.is_linked = True
Example #20
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 #21
Source File: key.py From checklocktimeverify-demos with GNU General Public License v3.0 | 6 votes |
def verify(self, hash, sig): # pylint: disable=redefined-builtin """Verify a DER signature""" if not sig: return False # New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first. norm_sig = ctypes.c_void_p(0) _ssl.d2i_ECDSA_SIG(ctypes.byref(norm_sig), ctypes.byref(ctypes.c_char_p(sig)), len(sig)) derlen = _ssl.i2d_ECDSA_SIG(norm_sig, 0) if derlen == 0: _ssl.ECDSA_SIG_free(norm_sig) return False norm_der = ctypes.create_string_buffer(derlen) _ssl.i2d_ECDSA_SIG(norm_sig, ctypes.byref(ctypes.pointer(norm_der))) _ssl.ECDSA_SIG_free(norm_sig) # -1 = error, 0 = bad sig, 1 = good return _ssl.ECDSA_verify(0, hash, len(hash), norm_der, derlen, self.k) == 1
Example #22
Source File: spi.py From Adafruit_Python_PureIO with MIT License | 6 votes |
def readbytes(self, length, max_speed_hz=0, bits_per_word=0, delay=0): """Perform half-duplex SPI read as a binary string """ receive_buffer = create_string_buffer(length) spi_ioc_transfer = struct.pack( SPI._IOC_TRANSFER_FORMAT, 0, addressof(receive_buffer), length, max_speed_hz, delay, bits_per_word, 0, 0, 0, 0, ) ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer) return string_at(receive_buffer, length)
Example #23
Source File: spi.py From Adafruit_Python_PureIO with MIT License | 5 votes |
def transfer(self, data, max_speed_hz=0, bits_per_word=0, delay=0): """Perform full-duplex SPI transfer """ data = array.array("B", data).tostring() receive_data = [] chunks = [ data[i : i + SPI_CHUNK_SIZE] for i in range(0, len(data), SPI_CHUNK_SIZE) ] for chunk in chunks: length = len(chunk) receive_buffer = create_string_buffer(length) transmit_buffer = create_string_buffer(chunk) spi_ioc_transfer = struct.pack( SPI._IOC_TRANSFER_FORMAT, addressof(transmit_buffer), addressof(receive_buffer), length, max_speed_hz, delay, bits_per_word, 0, 0, 0, 0, ) ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer) receive_data += string_at(receive_buffer, length) return receive_data
Example #24
Source File: epanet2.py From epynet with Apache License 2.0 | 5 votes |
def ENgetnodeid(self, index): """Retrieves the ID label of a node with a specified index. Arguments: index: node index""" label = ctypes.create_string_buffer(self._max_label_len) ierr= self._lib.EN_getnodeid(self.ph, index, ctypes.byref(label)) if ierr!=0: raise ENtoolkitError(self, ierr) return label.value.decode(self.charset)
Example #25
Source File: config.py From EDMarketConnector with GNU General Public License v2.0 | 5 votes |
def KnownFolderPath(guid): buf = ctypes.c_wchar_p() if SHGetKnownFolderPath(ctypes.create_string_buffer(guid.bytes_le), 0, 0, ctypes.byref(buf)): return None retval = buf.value # copy data CoTaskMemFree(buf) # and free original return retval
Example #26
Source File: inotify_file_watcher.py From browserscope with Apache License 2.0 | 5 votes |
def _add_watch_for_path(self, path): logging.debug('_add_watch_for_path(%r)', path) for dirpath, directories, _ in itertools.chain( [('', [path], None)], os.walk(path, topdown=True, followlinks=True)): for directory in directories: directory_path = os.path.join(dirpath, directory) # dirpath cannot be used as the parent directory path because it is the # empty string for symlinks :-( parent_path = os.path.dirname(directory_path) watch_descriptor = InotifyFileWatcher._libc.inotify_add_watch( self._inotify_fd, ctypes.create_string_buffer(directory_path), _INTERESTING_INOTIFY_EVENTS) if watch_descriptor < 0: if ctypes.get_errno() == errno.ENOSPC: logging.warning( 'There are too many directories in your application for ' 'changes in all of them to be monitored. You may have to ' 'restart the development server to see some changes to your ' 'files.') return error = OSError('could not add watch for %r' % directory_path) error.errno = ctypes.get_errno() error.strerror = errno.errorcode[ctypes.get_errno()] error.filename = directory_path raise error if parent_path in self._directory_to_subdirs: self._directory_to_subdirs[parent_path].add(directory_path) self._watch_to_directory[watch_descriptor] = directory_path self._directory_to_watch_descriptor[directory_path] = watch_descriptor self._directory_to_subdirs[directory_path] = set()
Example #27
Source File: key.py From checklocktimeverify-demos with GNU General Public License v3.0 | 5 votes |
def sign(self, hash): # pylint: disable=redefined-builtin if not isinstance(hash, bytes): raise TypeError('Hash must be bytes instance; got %r' % hash.__class__) if len(hash) != 32: raise ValueError('Hash must be exactly 32 bytes long') sig_size0 = ctypes.c_uint32() sig_size0.value = _ssl.ECDSA_size(self.k) mb_sig = ctypes.create_string_buffer(sig_size0.value) result = _ssl.ECDSA_sign(0, hash, len(hash), mb_sig, ctypes.byref(sig_size0), self.k) assert 1 == result if bitcoin.core.script.IsLowDERSignature(mb_sig.raw[:sig_size0.value]): return mb_sig.raw[:sig_size0.value] else: return self.signature_to_low_s(mb_sig.raw[:sig_size0.value])
Example #28
Source File: key.py From checklocktimeverify-demos with GNU General Public License v3.0 | 5 votes |
def _check_res_void_p(val, func, args): # pylint: disable=unused-argument if val == 0: errno = _ssl.ERR_get_error() errmsg = ctypes.create_string_buffer(120) _ssl.ERR_error_string_n(errno, errmsg, 120) raise OpenSSLException(errno, str(errmsg.value)) return ctypes.c_void_p(val)
Example #29
Source File: epanet2.py From epynet with Apache License 2.0 | 5 votes |
def ENgetlinkid(self, index): """Retrieves the ID label of a link with a specified index. Arguments: index: link index""" label = ctypes.create_string_buffer(self._max_label_len) ierr= self._lib.EN_getlinkid(self.ph, index, ctypes.byref(label)) if ierr!=0: raise ENtoolkitError(self, ierr) return label.value.decode(self.charset)
Example #30
Source File: spi.py From Adafruit_Python_PureIO with MIT License | 5 votes |
def writebytes(self, data, max_speed_hz=0, bits_per_word=0, delay=0): """Perform half-duplex SPI write. """ data = array.array("B", data).tostring() # length = len(data) chunks = [ data[i : i + SPI_CHUNK_SIZE] for i in range(0, len(data), SPI_CHUNK_SIZE) ] for chunk in chunks: length = len(chunk) transmit_buffer = create_string_buffer(chunk) spi_ioc_transfer = struct.pack( SPI._IOC_TRANSFER_FORMAT, addressof(transmit_buffer), 0, length, max_speed_hz, delay, bits_per_word, 0, 0, 0, 0, ) try: ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer) except TimeoutError: raise Exception( "ioctl timeout. Please try a different SPI frequency or less data." )