Python源码示例:ctypes.create_string_buffer()

示例1
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) 
示例2
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) 
示例3
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 
示例4
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 
示例5
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 
示例6
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]) 
示例7
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 
示例8
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]) 
示例9
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 
示例10
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 
示例11
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 
示例12
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 
示例13
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 
示例14
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) 
示例15
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 
示例16
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 
示例17
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 
示例18
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 
示例19
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) 
示例20
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) 
示例21
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) 
示例22
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 
示例23
def _get_terminal_size_windows(self):
        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 
示例24
def _get_terminal_size(fd):
        columns = lines = 0

        try:
            handle = _handles[fd]
            csbi = create_string_buffer(22)
            res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
            if res:
                res = struct.unpack("hhhhHhhhhhh", csbi.raw)
                left, top, right, bottom = res[5:9]
                columns = right - left + 1
                lines = bottom - top + 1
        except Exception:
            pass

        return terminal_size(columns, lines) 
示例25
def buffer_from_bytes(initializer):
        return ctypes.create_string_buffer(initializer) 
示例26
def siesta_hsx_read(fname, force_gamma=None): 

  fname = create_string_buffer(fname.encode())
  if force_gamma is None: 
    ft = c_int64(-1)
  elif force_gamma: 
    ft = c_int64(1)
  elif not force_gamma: 
    ft = c_int64(2)
  
  bufsize, row_ptr_size, col_ind_size = c_int64(), c_int64(), c_int64()
  libnao.siesta_hsx_size(fname, ft, bufsize, row_ptr_size, col_ind_size)
  if bufsize.value<=0 or row_ptr_size.value <= 0 or col_ind_size.value <= 0: return None
  
  dat = empty(bufsize.value, dtype=np.float32)
  dimensions = empty(4, dtype=np.int64)
  row_ptr = empty(row_ptr_size.value, dtype=np.int64)
  col_ind = empty(col_ind_size.value, dtype=np.int64)

  libnao.siesta_hsx_read(fname, ft, dat.ctypes.data_as(POINTER(c_float)),
      row_ptr.ctypes.data_as(POINTER(c_int64)), row_ptr_size,
      col_ind.ctypes.data_as(POINTER(c_int64)), col_ind_size,
      dimensions.ctypes.data_as(POINTER(c_int64)))
  return dat, row_ptr, col_ind, dimensions

#
#
# 
示例27
def siesta_wfsx_book_read_py(fname, nreim):
  """ Creates buffer for integer data from .WFSX files """
  name = create_string_buffer(fname.encode())
  bufsize = c_int64(-999)
  ios = c_int64(22)
  libnao.siesta_wfsx_book_size(name, c_int64(nreim), bufsize, ios)
  if ios.value!=0 : return None
  idat = empty(bufsize.value, dtype=np.int64)
  libnao.siesta_wfsx_book_read(name, c_int64(nreim), idat.ctypes.data_as(POINTER(c_int64)), ios)
  if ios.value!=0 : return None
  return idat

#
#
# 
示例28
def siesta_wfsx_dread(w, nreim):
  ddata = empty(w.nkpoints*w.nspin*w.norbs + + w.nkpoints*3)
  ios = c_int64(-999)
  libnao.siesta_wfsx_dread(create_string_buffer(w.fname.encode()), c_int64(nreim), ddata.ctypes.data_as(POINTER(c_double)), ios)
  if ios.value!=0 : raise RuntimeError('ios!=0 %d'%(ios.value))
  return ddata

#
#
# 
示例29
def siesta_wfsx_sread(w, sdata, nreim):
  name = create_string_buffer(w.fname.encode())
  bufsize = w.nkpoints*w.nspin*w.norbs**2*w.nreim
  ios = c_int64(-999)
  libnao.siesta_wfsx_sread(name, c_int64(nreim), sdata.ctypes.data_as(POINTER(c_float)), ios)
  if ios.value!=0 : raise RuntimeError('ios!=0 %d'%(ios.value)) 
示例30
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