當前位置: 首頁>>代碼示例>>Python>>正文


Python ctypes.create_string_buffer方法代碼示例

本文整理匯總了Python中ctypes.create_string_buffer方法的典型用法代碼示例。如果您正苦於以下問題:Python ctypes.create_string_buffer方法的具體用法?Python ctypes.create_string_buffer怎麽用?Python ctypes.create_string_buffer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ctypes的用法示例。


在下文中一共展示了ctypes.create_string_buffer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _get_terminal_size

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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) 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:18,代碼來源:shutil_get_terminal_size.py

示例2: lcs

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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) 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:25,代碼來源:lcs.py

示例3: hamming_klcs

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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) 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:24,代碼來源:lcs.py

示例4: _cf_string_to_unicode

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:25,代碼來源:low_level.py

示例5: info

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:Parrot-Developers,項目名稱:olympe,代碼行數:22,代碼來源:pdraw.py

示例6: getChannelData_Name

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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]) 
開發者ID:diyjac,項目名稱:Udacity-SDC-Radar-Driver-Micro-Challenge,代碼行數:22,代碼來源:canlib.py

示例7: getChannelData_DriverName

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:diyjac,項目名稱:Udacity-SDC-Radar-Driver-Micro-Challenge,代碼行數:18,代碼來源:canlib.py

示例8: _get_terminal_size_windows

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:aaronjanse,項目名稱:asciidots,代碼行數:20,代碼來源:terminalsize.py

示例9: _createShader

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:ratcave,項目名稱:ratcave,代碼行數:27,代碼來源:shader.py

示例10: link

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:ratcave,項目名稱:ratcave,代碼行數:19,代碼來源:shader.py

示例11: enable_debug_privilege

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:skelsec,項目名稱:minidump,代碼行數:23,代碼來源:privileges.py

示例12: readbytes

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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) 
開發者ID:adafruit,項目名稱:Adafruit_Python_PureIO,代碼行數:21,代碼來源:spi.py

示例13: _get_terminal_size_windows

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:terminal.py

示例14: process_data

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:realityone,項目名稱:libcet,代碼行數:21,代碼來源:cet.py

示例15: verify

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import create_string_buffer [as 別名]
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 
開發者ID:petertodd,項目名稱:checklocktimeverify-demos,代碼行數:22,代碼來源:key.py


注:本文中的ctypes.create_string_buffer方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。