Python ctypes 模块,c_int8() 实例源码

我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用ctypes.c_int8()

项目:zika-pipeline    作者:zibraproject    | 项目源码 | 文件源码
def to_int(seq, lEle, dEle2Int):
    """
    translate a sequence into numbers
    @param  seq   a sequence
    """
    num_decl = len(seq) * ct.c_int8
    num = num_decl()
    for i,ele in enumerate(seq):
        try:
            n = dEle2Int[ele]
        except KeyError:
            n = dEle2Int[lEle[-1]]
        finally:
            num[i] = n

    return num
项目:Gilgamesh    作者:AndreaOrru    | 项目源码 | 文件源码
def _branch(self, i):
        """Emulate all branch instructions.

        Note that a conditional branch will cause another
        CPU instance to be created and run.

        Args:
            i: The instruction.

        Returns:
            The target of the branch.
        """
        if i.mnemonic in ('bra', 'brl'):
            return self._branch_always(i)
        else:
            branch_pc = self.pc + c_int8(i.operand).value
            branch_cpu = CPU(self._analyzer, self._rom, branch_pc, self.flags)
            branch_cpu.run()
            return branch_pc
项目:nifpga-python    作者:ni    | 项目源码 | 文件源码
def _return_ctype(self):
        """ Returns the associated ctype of a given datatype. """
        _datatype_ctype = {
            DataType.Bool: ctypes.c_uint8,
            DataType.I8: ctypes.c_int8,
            DataType.U8: ctypes.c_uint8,
            DataType.I16: ctypes.c_int16,
            DataType.U16: ctypes.c_uint16,
            DataType.I32: ctypes.c_int32,
            DataType.U32: ctypes.c_uint32,
            DataType.I64: ctypes.c_int64,
            DataType.U64: ctypes.c_uint64,
            DataType.Sgl: ctypes.c_float,
            DataType.Dbl: ctypes.c_double,
        }
        return _datatype_ctype[self]
项目:LoReAn    作者:lfaino    | 项目源码 | 文件源码
def to_int(seq, lEle, dEle2Int):
    """
    it is used for the alignment of the primers to the reads
    :param seq: 
    :param lEle: 
    :param dEle2Int: 
    :return: 
    """
    num_decl = len(seq) * ct.c_int8
    num = num_decl()
    for i,ele in enumerate(seq):
        try:
            n = dEle2Int[ele]
        except KeyError:
            n = dEle2Int[lEle[-1]]
        finally:
            num[i] = n
    return num
项目:latools    作者:freeseek    | 项目源码 | 文件源码
def getsig(filename,clib):
    infile = gzip.open(filename,'rb')
    try:
        lines = infile.readlines()
    except IOError:
        infile.close()
        infile = open(filename,'rt')
        lines = infile.readlines()
    infile.close()
    T = len(lines)
    n = len(bytes.decode(lines[0]).split()[3:])
    chrom = (ctypes.c_long * T)()
    pos = (ctypes.c_long * T)()
    obs = np.zeros((T,n),dtype=ctypes.c_int8)
    lines_p = (ctypes.c_char_p * T)()
    lines_p[:] = lines
    clib.getsig.restype = None;
    clib.getsig(chrom,pos,obs.ctypes.data_as(ctypes.c_void_p),
                ctypes.c_long(T),ctypes.c_long(n),lines_p)
    return n/2, chrom, pos, obs

# retrieve the genotype likelihoods
项目:iofus    作者:numaru    | 项目源码 | 文件源码
def write_var_int(self, value):
        byte = 0
        out = ByteArray()
        if value >= 0 and value <= 0x7F:
            out.write_byte(value)
            self.write_bytes(out)
            return
        remaining = value
        buffer_array = ByteArray()
        while remaining != 0:
            buffer_array.write_byte(remaining & 0x7F)
            buffer_array.seek(len(buffer_array) - 1)
            byte = buffer_array.read_byte()
            remaining = _lrshift32(remaining, 7)
            if remaining > 0:
                byte = ctypes.c_int8(byte | 0x80).value
            out.write_byte(byte)
        self.write_bytes(out)
项目:iofus    作者:numaru    | 项目源码 | 文件源码
def write_var_short(self, value):
        byte = 0
        if value > 32767 or value < -32768:
            raise RuntimeError("Forbidden value")
        out = ByteArray()
        if value >= 0 and value <= 0x7F:
            out.write_byte(value)
            self.write_bytes(out)
            return
        remaining = value & 65535
        buffer_array = ByteArray()
        while remaining != 0:
            buffer_array.write_byte(remaining & 0x7F)
            buffer_array.seek(len(buffer_array) - 1)
            byte = buffer_array.read_byte()
            remaining = _lrshift32(remaining, 7)
            if remaining > 0:
                byte = ctypes.c_int8(byte | 0x80).value
            out.write_byte(byte)
        self.write_bytes(out)
项目:flask-docjson    作者:elemepi    | 项目源码 | 文件源码
def validate_i8(val, p, key=None):
    if isinstance(val, int) and ctypes.c_int8(val).value == val:
        return
    raise_validation_error(ErrInvalidI8, val, p, key=key)
项目:Gilgamesh    作者:AndreaOrru    | 项目源码 | 文件源码
def _branch_always(self, i):
        """Emulate the BRA and BRL instructions.

        Args:
            i: The instruction.

        Returns:
            The target of the branch.
        """
        if i.address_mode == Mode.RELATIVE:
            self.pc += c_int8(i.operand).value
        elif i.address_mode == Mode.RELATIVE_LONG:
            self.pc += c_int16(i.operand).value
        return self.pc
项目:idascripts    作者:ctfhacker    | 项目源码 | 文件源码
def struct(cls, ea, **sid):
        """Return the structure_t at address ``ea`` as a dict of ctypes.
        If the structure ``sid`` is specified, then use that specific structure type.
        """
        ea = interface.address.within(ea)

        if any(n in sid for n in ('sid','struc','structure','id')):
            res = sid['sid'] if 'sid' in sid else sid['struc'] if 'struc' in sid else sid['structure'] if 'structure' in sid else sid['id'] if 'id' in sid else None
            sid = res.id if isinstance(res, structure.structure_t) else res
        else:
            sid = type.structure.id(ea)

        st = structure.instance(sid, offset=ea)
        typelookup = {
            (int,-1) : ctypes.c_int8, (int,1) : ctypes.c_uint8,
            (int,-2) : ctypes.c_int16, (int,2) : ctypes.c_uint16,
            (int,-4) : ctypes.c_int32, (int,4) : ctypes.c_uint32,
            (int,-8) : ctypes.c_int64, (int,8) : ctypes.c_uint64,
            (float,4) : ctypes.c_float, (float,8) : ctypes.c_double,
        }

        res = {}
        for m in st.members:
            t, val = m.type, read(m.offset, m.size) or ''
            try:
                ct = typelookup[t]
            except KeyError:
                ty, sz = t if isinstance(t, __builtin__.tuple) else (m.type, 0)
                if isinstance(t, __builtin__.list):
                    t = typelookup[tuple(ty)]
                    ct = t*sz
                elif ty in (chr,str):
                    ct = ctypes.c_char*sz
                else:
                    ct = None
            finally:
                res[m.name] = val if any(_ is None for _ in (ct,val)) else ctypes.cast(ctypes.pointer(ctypes.c_buffer(val)),ctypes.POINTER(ct)).contents
        return res
项目:latools    作者:freeseek    | 项目源码 | 文件源码
def getla(filename,clib):
    if filename == '-':
        infile = sys.stdin
        line = infile.readline()
    else:
        infile = gzip.open(filename,'rb')
        try:
            line = infile.readline()
        except IOError:
            infile.close()
            infile = open(filename,'rt')
            line = infile.readline()
    lines = infile.readlines()
    infile.close()
    samples = bytes.decode(line).split()[3:]
    n = len(lines)
    m = len(samples)
    chrom = (ctypes.c_long * n)()
    start = (ctypes.c_long * n)()
    end = (ctypes.c_long * n)()
    la = np.zeros((n,m),dtype=ctypes.c_int8)
    lines_p = (ctypes.c_char_p * n)()
    lines_p[:] = lines

    clib.getla.restype = None;
    clib.getla(chrom,start,end,la.ctypes.data_as(ctypes.c_void_p),
               ctypes.c_long(n),ctypes.c_long(m),lines_p)
    return samples, chrom, start, end, la


# retrieve the ancestry signatures matrix
项目:kotori    作者:daq-tools    | 项目源码 | 文件源码
def setup(self):

        # counter "ValueError: number of bits invalid for bit field"
        monkeypatch_pyclibrary_ctypes_struct()

        # register header- and library paths
        # https://pyclibrary.readthedocs.org/en/latest/get_started/configuration.html#specifying-headers-and-libraries-locations
        # TODO: this probably acts on a global basis; think about it
        if self.include_path:
            add_header_locations([self.include_path])
        if self.library_path:
            add_library_locations([self.library_path])

        # define extra types suitable for embedded use
        types = {
            'uint8_t': c_uint8,
            'uint16_t': c_uint16,
            'uint32_t': c_uint32,
            'int8_t': c_int8,
            'int16_t': c_int16,
            'int32_t': c_int32,
            }

        # TODO: this probably acts on a global basis; think about it
        if not (CParser._init or CLibrary._init):
            auto_init(extra_types=types)
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_x():
    """Returns the X position of the joystick.

    Note: An exception is thrown if it fails to read the X position from the
    chip.
    """
    pos_x = ctypes.c_int8(0)
    ret = _LIB.joystick_click_get_x(ctypes.byref(pos_x))
    if ret < 0:
        raise Exception("joystick click get x failed")
    return pos_x.value
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_y():
    """Returns the Y position of the joystick.

    Note: An exception is thrown if it fails to read the Y position from the
    chip.
    """
    pos_y = ctypes.c_int8(0)
    ret = _LIB.joystick_click_get_y(ctypes.byref(pos_y))
    if ret < 0:
        raise Exception("joystick click get y failed")
    return pos_y.value
项目:PyLetMeCreate    作者:CreatorDev    | 项目源码 | 文件源码
def get_position():
    """Returns the X position of the joystick.

    Note: An exception is thrown if it fails to read the position from the
    chip.
    """
    pos_x = ctypes.c_int8(0)
    pos_y = ctypes.c_int8(0)
    ret = _LIB.joystick_click_get_position(ctypes.byref(pos_x),
                                           ctypes.byref(pos_y))
    if ret < 0:
        raise Exception("joystick click get position failed")
    return (pos_x.value, pos_y.value)
项目:python-vulkan-wrapper    作者:gabdube    | 项目源码 | 文件源码
def translate_type(t):
    table = { 
        "float": 'c_float',
        "uint32_t": 'c_uint32', 
        "uint64_t": 'c_uint64',
        "size_t": 'c_size_t',
        "float": 'c_float',
        'int32_t': 'c_int32',
        'int': 'c_int32',
        'uint8_t': 'c_int8',
        "char": "c_char",
        "void": "None", 
        "void*": "c_void_p", 
        "const void*": 'c_void_p',
        "const char*": 'c_char_p',
        "const char* const*": 'POINTER(c_char_p)',
        "struct wl_display*": "POINTER(wl_display)",
        "struct wl_surface*": "POINTER(wl_surface)",
        "const ObjectTableEntryNVX* const*": "POINTER(POINTER(ObjectTableEntryNVX))",
        'v': ''
     }

    if t in table.keys():
        return table[t]

    if t.endswith("*"):
        if t.startswith("const"):
            ttype = t[6:len(t)-1]
            ttype = table[ttype] if ttype in table else ttype
            return "POINTER({})".format(ttype)
        else:
            ttype = t[:len(t)-1]
            ttype = table[ttype] if ttype in table else ttype
            return "POINTER({})".format(ttype)

    return t
项目:chaquopy    作者:chaquo    | 项目源码 | 文件源码
def test_output_arg(self):
        String = jclass('java.lang.String')
        string = String(u'\u1156\u2278\u3390\u44AB')
        for btarray in ([0] * 4,
                        (0,) * 4,
                        jarray(jbyte)([0] * 4)):
            # This version of getBytes returns the 8 low-order of each Unicode character.
            string.getBytes(0, 4, btarray, 0)
            if not isinstance(btarray, tuple):
                self.assertEquals(btarray, [ctypes.c_int8(x).value
                                            for x in [0x56, 0x78, 0x90, 0xAB]])