Python ctypes.c_char_p() Examples

The following are 30 code examples of ctypes.c_char_p(). 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 vote down vote up
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: key.py    From checklocktimeverify-demos with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: recordio.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def write(self, buf):
        """Inserts a string buffer as a record.

        Example usage:
        ----------
        >>> record = mx.recordio.MXRecordIO('tmp.rec', 'w')
        >>> for i in range(5):
        ...    record.write('record_%d'%i)
        >>> record.close()

        Parameters
        ----------
        buf : string (python2), bytes (python3)
            Buffer to write.
        """
        assert self.writable
        check_call(_LIB.MXRecordIOWriterWriteRecord(self.handle,
                                                    ctypes.c_char_p(buf),
                                                    ctypes.c_size_t(len(buf)))) 
Example #4
Source File: symbol.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def list_arguments(self):
        """Lists all the arguments in the symbol.

        Example
        -------
        >>> a = mx.sym.var('a')
        >>> b = mx.sym.var('b')
        >>> c = a + b
        >>> c.list_arguments
        ['a', 'b']

        Returns
        -------
        args : list of string
            List containing the names of all the arguments required to compute the symbol.
        """
        size = ctypes.c_uint()
        sarr = ctypes.POINTER(ctypes.c_char_p)()
        check_call(_LIB.MXSymbolListArguments(
            self.handle, ctypes.byref(size), ctypes.byref(sarr)))
        return [py_str(sarr[i]) for i in range(size.value)] 
Example #5
Source File: base.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def c_str_array(strings):
        """Create ctypes const char ** from a list of Python strings.

        Parameters
        ----------
        strings : list of string
            Python strings.

        Returns
        -------
        (ctypes.c_char_p * len(strings))
            A const char ** pointer that can be passed to C API.
        """
        arr = (ctypes.c_char_p * len(strings))()
        arr[:] = strings
        return arr 
Example #6
Source File: base.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def c_str(string):
        """Create ctypes char * from a Python string.

        Parameters
        ----------
        string : string type
            Python string.

        Returns
        -------
        str : c_char_p
            A char pointer that can be passed to C API.

        Examples
        --------
        >>> x = mx.base.c_str("Hello, World")
        >>> print(x.value)
        b"Hello, World"
        """
        return ctypes.c_char_p(string.encode('utf-8')) 
Example #7
Source File: base.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def c_str_array(strings):
        """Create ctypes const char ** from a list of Python strings.

        Parameters
        ----------
        strings : list of string
            Python strings.

        Returns
        -------
        (ctypes.c_char_p * len(strings))
            A const char ** pointer that can be passed to C API.
        """
        arr = (ctypes.c_char_p * len(strings))()
        arr[:] = [s.encode('utf-8') for s in strings]
        return arr 
Example #8
Source File: symbol.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def name(self):
        """Gets name string from the symbol, this function only works for non-grouped symbol.

        Returns
        -------
        value : str
            The name of this symbol, returns ``None`` for grouped symbol.
        """
        ret = ctypes.c_char_p()
        success = ctypes.c_int()
        check_call(_LIB.MXSymbolGetName(
            self.handle, ctypes.byref(ret), ctypes.byref(success)))
        if success.value != 0:
            return py_str(ret.value)
        else:
            return None 
Example #9
Source File: symbol.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def list_attr(self, recursive=False):
        """Gets all attributes from the symbol.

        Example
        -------
        >>> data = mx.sym.Variable('data', attr={'mood': 'angry'})
        >>> data.list_attr()
        {'mood': 'angry'}

        Returns
        -------
        ret : Dict of str to str
            A dictionary mapping attribute keys to values.
        """
        if recursive:
            raise DeprecationWarning("Symbol.list_attr with recursive=True has been deprecated. "
                                     "Please use attr_dict instead.")
        size = mx_uint()
        pairs = ctypes.POINTER(ctypes.c_char_p)()
        f_handle = _LIB.MXSymbolListAttrShallow
        check_call(f_handle(self.handle, ctypes.byref(size), ctypes.byref(pairs)))
        return {py_str(pairs[i * 2]): py_str(pairs[i * 2 + 1]) for i in range(size.value)} 
Example #10
Source File: base.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def c_str(string):
        """Create ctypes char * from a Python string.

        Parameters
        ----------
        string : string type
            Python string.

        Returns
        -------
        str : c_char_p
            A char pointer that can be passed to C API.

        Examples
        --------
        >>> x = mx.base.c_str("Hello, World")
        >>> print x.value
        Hello, World
        """
        return ctypes.c_char_p(string) 
Example #11
Source File: executor.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def set_monitor_callback(self, callback):
        """Install callback for monitor.

        Parameters
        ----------
        callback : function
            Takes a string and an NDArrayHandle.

        Examples
        --------
        >>> def mon_callback(*args, **kwargs):
        >>>     print("Do your stuff here.")
        >>>
        >>> texe.set_monitor_callback(mon_callback)
        """
        cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
        self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
        check_call(_LIB.MXExecutorSetMonitorCallback(
            self.handle,
            self._monitor_callback,
            None)) 
Example #12
Source File: epanet2.py    From epynet with Apache License 2.0 6 votes vote down vote up
def ENepanet(self,nomeinp, nomerpt='', nomebin='', vfunc=None):
        """Runs a complete EPANET simulation.

        Arguments:
        nomeinp: name of the input file
        nomerpt: name of an output report file
        nomebin: name of an optional binary output file
        vfunc  : pointer to a user-supplied function which accepts a character string as its argument."""  
        if vfunc is not None:
            CFUNC = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p)
            callback= CFUNC(vfunc)
        else:
            callback= None
        ierr= self._lib.EN_epanet(self.ph, ctypes.c_char_p(nomeinp.encode()), 
                            ctypes.c_char_p(nomerpt.encode()), 
                            ctypes.c_char_p(nomebin.encode()), 
                            callback)
        if ierr!=0: raise ENtoolkitError(self, ierr) 
Example #13
Source File: firefox_decrypt.py    From firefox_decrypt with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        # Locate libnss and try loading it
        self.NSS = None
        self.load_libnss()

        SlotInfoPtr = ct.POINTER(self.PK11SlotInfo)
        SECItemPtr = ct.POINTER(self.SECItem)

        self._set_ctypes(ct.c_int, "NSS_Init", ct.c_char_p)
        self._set_ctypes(ct.c_int, "NSS_Shutdown")
        self._set_ctypes(SlotInfoPtr, "PK11_GetInternalKeySlot")
        self._set_ctypes(None, "PK11_FreeSlot", SlotInfoPtr)
        self._set_ctypes(ct.c_int, "PK11_CheckUserPassword", SlotInfoPtr, ct.c_char_p)
        self._set_ctypes(ct.c_int, "PK11SDR_Decrypt", SECItemPtr, SECItemPtr, ct.c_void_p)
        self._set_ctypes(None, "SECITEM_ZfreeItem", SECItemPtr, ct.c_int)

        # for error handling
        self._set_ctypes(ct.c_int, "PORT_GetError")
        self._set_ctypes(ct.c_char_p, "PR_ErrorToName", ct.c_int)
        self._set_ctypes(ct.c_char_p, "PR_ErrorToString", ct.c_int, ct.c_uint32) 
Example #14
Source File: dialogs.py    From pylibui with MIT License 6 votes vote down vote up
def uiOpenFile(parent):
    """
    Creates a new open file dialog.

    :param parent: uiWindow
    :return: string
    """

    clibui.uiOpenFile.restype = ctypes.c_char_p
    path = clibui.uiOpenFile(parent)

    if path is not None:
        return path.decode()
    else:
        return ""


# - char *uiSaveFile(uiWindow *parent); 
Example #15
Source File: s2v_lib.py    From pytorch_structure2vec with MIT License 6 votes vote down vote up
def __init__(self, args):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        self.lib = ctypes.CDLL('%s/build/dll/libs2v.so' % dir_path)

        self.lib.GetGraphStruct.restype = ctypes.c_void_p
        self.lib.PrepareBatchGraph.restype = ctypes.c_int
        self.lib.PrepareMeanField.restype = ctypes.c_int
        self.lib.PrepareLoopyBP.restype = ctypes.c_int
        self.lib.NumEdgePairs.restype = ctypes.c_int

        if sys.version_info[0] > 2:
            args = [arg.encode() for arg in args]  # str -> bytes for each element in args
        arr = (ctypes.c_char_p * len(args))()
        arr[:] = args
        self.lib.Init(len(args), arr)

        self.batch_graph_handle = ctypes.c_void_p(self.lib.GetGraphStruct()) 
Example #16
Source File: simple_julia_py.py    From restrain-jit with MIT License 6 votes vote down vote up
def get_jl_lib(conf) -> JuliaPreLoad:
    jl = conf["julia"]
    lib_path = jl["lib"]
    sys_image = jl["image"]
    binary = jl["bin"]

    lib = ctypes.PyDLL(lib_path, ctypes.RTLD_GLOBAL)
    lib.jl_eval_string.argtypes = [ctypes.c_char_p]
    lib.jl_eval_string.restype = ctypes.c_void_p

    try:
        init = lib.jl_init_with_image
    except AttributeError:
        init = lib.jl_init_with_image__threading

    return JuliaPreLoad(
        lambda: init(binary.encode(), sys_image.encode()), lib) 
Example #17
Source File: window.py    From pylibui with MIT License 6 votes vote down vote up
def uiNewWindow(title, width, height, hasMenubar):
    """
    Creates a new Window.

    :param title: string
    :param width: int
    :param height: int
    :param hasMenubar: int
    :return: uiWindow
    """

    # Set return type
    clibui.uiNewWindow.restype = ctypes.POINTER(uiWindow)

    return clibui.uiNewWindow(
        ctypes.c_char_p(bytes(title, 'utf-8')), width, height, hasMenubar) 
Example #18
Source File: window.py    From pylibui with MIT License 6 votes vote down vote up
def uiWindowTitle(window):
    """
    Returns the window's title.

    :param window: uiWindow
    :return: string
    """

    # Set return type
    clibui.uiWindowTitle.restype = ctypes.c_char_p

    title = clibui.uiWindowTitle(window)
    return title.decode()


# - void uiWindowSetTitle(uiWindow *w, const char *title); 
Example #19
Source File: key.py    From checklocktimeverify-demos with GNU General Public License v3.0 6 votes vote down vote up
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 #20
Source File: shader.py    From ratcave with MIT License 6 votes vote down vote up
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 #21
Source File: dialogs.py    From pylibui with MIT License 6 votes vote down vote up
def uiSaveFile(parent):
    """
    Creates a new save file dialog.

    :param parent: uiWindow
    :return: string
    """

    clibui.uiSaveFile.restype = ctypes.c_char_p
    path = clibui.uiSaveFile(parent)

    if path is not None:
        return path.decode()
    else:
        return ""


# - void uiMsgBox(uiWindow *parent, const char *title, const char *description); 
Example #22
Source File: opencv.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def imdecode(str_img, flag=1):
    """Decode image from str buffer.
    Wrapper for cv2.imdecode that uses mx.nd.NDArray

    Parameters
    ----------
    str_img : str
        str buffer read from image file
    flag : int
        same as flag for cv2.imdecode
    Returns
    -------
    img : NDArray
        decoded image in (width, height, channels)
        with BGR color channel order
    """
    hdl = NDArrayHandle()
    check_call(_LIB.MXCVImdecode(ctypes.c_char_p(str_img),
                                 mx_uint(len(str_img)),
                                 flag, ctypes.byref(hdl)))
    return mx.nd.NDArray(hdl) 
Example #23
Source File: checkbox.py    From pylibui with MIT License 5 votes vote down vote up
def uiCheckboxText(checkbox):
    """
    Returns the text of the checkbox.

    :param checkbox: uiCheckbox
    :return: string
    """

    clibui.uiCheckboxText.restype = ctypes.c_char_p
    text = clibui.uiCheckboxText(checkbox)

    return text.decode()


# - void uiCheckboxSetText(uiCheckbox *c, const char *text); 
Example #24
Source File: epanet2.py    From epynet with Apache License 2.0 5 votes vote down vote up
def ENgetcurveindex(self, curveId):
        j= ctypes.c_int()
        ierr= self._lib.EN_getcurveindex(self.ph, ctypes.c_char_p(curveId.encode(self.charset)), ctypes.byref(j))
        if ierr!=0: raise ENtoolkitError(self, ierr)
        return j.value 
Example #25
Source File: button.py    From pylibui with MIT License 5 votes vote down vote up
def uiButtonText(button):
    """
    Returns the text of the button.

    :param button: uiButton
    :return: string
    """
    clibui.uiButtonText.restype = ctypes.c_char_p
    text = clibui.uiButtonText(button)

    return text.decode()


# - void uiButtonSetText(uiButton *b, const char *text); 
Example #26
Source File: statx.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def statx(path):
    pathname = ctypes.c_char_p(utils.SmartStr(path))
    statxbuf = ctypes.create_string_buffer(ctypes.sizeof(Statx))

    lib = ctypes.CDLL(None, use_errno=True)
    syscall = lib.syscall

    # int statx(int dirfd, const char *pathname, int flags, unsigned int mask, struct statx *statxbuf);
    syscall.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_uint, ctypes.c_char_p]
    syscall.restype = ctypes.c_int

    if syscall(SYS_STATX, AT_FDCWD, pathname, AT_SYMLINK_NOFOLLOW, STATX_ALL, statxbuf):
        e = ctypes.get_errno()
        raise OSError(e, os.strerror(e), path)
    return Statx.from_buffer(statxbuf) 
Example #27
Source File: entry.py    From pylibui with MIT License 5 votes vote down vote up
def uiEntryText(entry):
    """
    Returns the text of the entry.

    :param entry: uiEntry
    :return: string
    """

    clibui.uiEntryText.restype = ctypes.c_char_p
    text = clibui.uiEntryText(entry)

    return text.decode()


# - void uiEntrySetText(uiEntry *e, const char *text); 
Example #28
Source File: key.py    From checklocktimeverify-demos with GNU General Public License v3.0 5 votes vote down vote up
def signature_to_low_s(self, sig):
        der_sig = ECDSA_SIG_st()
        _ssl.d2i_ECDSA_SIG(ctypes.byref(ctypes.pointer(der_sig)), ctypes.byref(ctypes.c_char_p(sig)), len(sig))
        group = _ssl.EC_KEY_get0_group(self.k)
        order = _ssl.BN_new()
        halforder = _ssl.BN_new()
        ctx = _ssl.BN_CTX_new()
        _ssl.EC_GROUP_get_order(group, order, ctx)
        _ssl.BN_rshift1(halforder, order)

        # Verify that s is over half the order of the curve before we actually subtract anything from it
        if _ssl.BN_cmp(der_sig.s, halforder) > 0:
          _ssl.BN_sub(der_sig.s, order, der_sig.s)

        _ssl.BN_free(halforder)
        _ssl.BN_free(order)
        _ssl.BN_CTX_free(ctx)

        derlen = _ssl.i2d_ECDSA_SIG(ctypes.pointer(der_sig), 0)
        if derlen == 0:
            _ssl.ECDSA_SIG_free(der_sig)
            return None
        new_sig = ctypes.create_string_buffer(derlen)
        _ssl.i2d_ECDSA_SIG(ctypes.pointer(der_sig), ctypes.byref(ctypes.pointer(new_sig)))
        _ssl.BN_free(der_sig.r)
        _ssl.BN_free(der_sig.s)

        return new_sig.raw 
Example #29
Source File: ifaces.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def get_iface(iface_type_str):
    iface_type = ctypes.create_string_buffer(iface_type_str)

    str_p = ctypes.c_char_p()
    pt = ctypes.pointer(str_p)

    if LIB.select_iface(iface_type, pt) != 0:
        return False

    return ctypes.string_at(str_p) 
Example #30
Source File: api.py    From typhon with MIT License 5 votes vote down vote up
def include_path_push(path):
    """
    Add path to include path of the ARTS runtime.

    Args:
        path(str): Path to add to the ARTS include path.
    """
    arts_api.include_path_push(c.c_char_p(path.encode()))