Python ctypes.c_int32() Examples

The following are 30 code examples of ctypes.c_int32(). 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: test_c_functions.py    From kernel_tuner with Apache License 2.0 6 votes vote down vote up
def test_ready_argument_list2():
    arg1 = numpy.array([1, 2, 3]).astype(numpy.float32)
    arg2 = numpy.int32(7)
    arg3 = numpy.float32(6.0)
    arguments = [arg1, arg2, arg3]

    cfunc = CFunctions()
    output = cfunc.ready_argument_list(arguments)
    print(output)

    output_arg1 = numpy.ctypeslib.as_array(output[0].ctypes, shape=arg1.shape)

    assert output_arg1.dtype == 'float32'
    assert isinstance(output[1].ctypes, C.c_int32)
    assert isinstance(output[2].ctypes, C.c_float)

    assert all(output_arg1 == arg1)
    assert output[1][1].value == arg2
    assert output[2][1].value == arg3 
Example #2
Source File: tecio.py    From handyscripts with MIT License 6 votes vote down vote up
def tecpolyface(num_faces, face_node_counts, face_nodes, face_left_elems, face_right_elems):
    tecio.tecpolyface142.restype=ctypes.c_int32
    tecio.tecpolyface142.argtypes=(
            ctypes.POINTER(ctypes.c_int32), # NumFaces
            ctypes.POINTER(ctypes.c_int32), # FaceNodeCounts array
            ctypes.POINTER(ctypes.c_int32), # FaceNodes array
            ctypes.POINTER(ctypes.c_int32), # Face Left Elems array
            ctypes.POINTER(ctypes.c_int32)) # Face Right Elems array

    face_node_count_array = None
    if face_node_counts:
        face_node_counts = np.asarray(face_node_counts,dtype=np.int32)
        face_node_count_array = ctypes.cast(face_node_counts.ctypes.data, ctypes.POINTER(ctypes.c_int32))

    face_nodes = np.asarray(face_nodes,dtype=np.int32)
    face_left_elems = np.asarray(face_left_elems,dtype=np.int32)
    face_right_elems = np.asarray(face_right_elems,dtype=np.int32)
    ret = tecio.tecpolyface142(
            ctypes.byref(ctypes.c_int32(num_faces)),
            face_node_count_array, #ctypes.cast(face_node_counts.ctypes.data, ctypes.POINTER(ctypes.c_int32)),
            ctypes.cast(face_nodes.ctypes.data, ctypes.POINTER(ctypes.c_int32)),
            ctypes.cast(face_left_elems.ctypes.data, ctypes.POINTER(ctypes.c_int32)),
            ctypes.cast(face_right_elems.ctypes.data, ctypes.POINTER(ctypes.c_int32)))
    if ret != 0:
        raise Exception("tecpolyface Error") 
Example #3
Source File: terminal.py    From terminal with MIT License 6 votes vote down vote up
def win32_shell_execute (self, op, filename, parameters, cwd = None):
		if self.unix:
			return False
		if not cwd:
			cwd = os.getcwd()
		self._win32_load_kernel()
		if not self.ShellExecute:
			try:
				import ctypes
				self.shell32 = ctypes.windll.LoadLibrary('shell32.dll')
				self.ShellExecute = self.shell32.ShellExecuteA
				args = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p ]
				args += [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32 ]
				self.ShellExecute.argtypes = args
				self.ShellExecute.restype = ctypes.wintypes.HINSTANCE
			except: pass
		if not self.ShellExecute:
			return False
		nShowCmd = 5
		self.ShellExecute(None, op, filename, parameters, cwd, nShowCmd)
		return True
	
	# win32 correct casing path: c:/windows -> C:\Windows 
Example #4
Source File: terminal.py    From terminal with MIT License 6 votes vote down vote up
def win32_path_long (self, path):
		if not path:
			return ''
		path = os.path.abspath(path)
		if self.unix:
			return path
		self._win32_load_kernel()
		if not self.GetLongPathName:
			try:
				import ctypes
				self.GetLongPathName = self.kernel32.GetLongPathNameA
				args = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32 ]
				self.GetLongPathName.argtypes = args
				self.GetLongPathName.restype = ctypes.c_uint32
			except: pass
		if not self.GetLongPathName:
			return path
		retval = self.GetLongPathName(path, self.textdata, 2048)
		longpath = self.textdata.value
		if retval <= 0:
			return ''
		return longpath 
Example #5
Source File: library.py    From picosdk-python-wrappers with ISC License 6 votes vote down vote up
def _python_open_any_unit(self, resolution):
        status = None
        if len(self._open_unit.argtypes) == 3:
            if resolution is None:
                resolution = self.DEFAULT_RESOLUTION
            chandle = c_int16()
            cresolution = c_int32()
            cresolution.value = resolution
            status = self._open_unit(byref(chandle), None, cresolution)
            handle = chandle.value
        elif len(self._open_unit.argtypes) == 2:
            chandle = c_int16()
            status = self._open_unit(byref(chandle), None)
            handle = chandle.value
        else:
            handle = self._open_unit()

        return handle, status 
Example #6
Source File: basic.py    From lambda-packs with MIT License 6 votes vote down vote up
def __init_from_csc(self, csc, params_str, ref_dataset):
        """Initialize data from a CSC matrix."""
        if len(csc.indices) != len(csc.data):
            raise ValueError('Length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data)))
        self.handle = ctypes.c_void_p()

        ptr_indptr, type_ptr_indptr, __ = c_int_array(csc.indptr)
        ptr_data, type_ptr_data, _ = c_float_array(csc.data)

        assert csc.shape[0] <= MAX_INT32
        csc.indices = csc.indices.astype(np.int32, copy=False)

        _safe_call(_LIB.LGBM_DatasetCreateFromCSC(
            ptr_indptr,
            ctypes.c_int(type_ptr_indptr),
            csc.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
            ptr_data,
            ctypes.c_int(type_ptr_data),
            ctypes.c_int64(len(csc.indptr)),
            ctypes.c_int64(len(csc.data)),
            ctypes.c_int64(csc.shape[0]),
            c_str(params_str),
            ref_dataset,
            ctypes.byref(self.handle)))
        return self 
Example #7
Source File: terminal.py    From terminal with MIT License 6 votes vote down vote up
def win32_path_full (self, path):
		if not path:
			return ''
		path = os.path.abspath(path)
		if self.unix:
			return path
		self._win32_load_kernel()
		if not self.GetFullPathName:
			try:
				import ctypes
				self.GetFullPathName = self.kernel32.GetFullPathNameA
				args = [ ctypes.c_char_p, ctypes.c_int32, ctypes.c_char_p ]
				self.GetFullPathName.argtypes = args + [ctypes.c_char_p]
				self.GetFullPathName.restype = ctypes.c_uint32
			except: pass
		if not self.GetFullPathName:
			return path
		retval = self.GetFullPathName(path, 2048, self.textdata, None)
		fullpath = self.textdata.value
		if retval <= 0:
			return ''
		return fullpath

	# win32 get long pathname 
Example #8
Source File: terminal.py    From terminal with MIT License 6 votes vote down vote up
def win32_path_short (self, path):
		if not path:
			return ''
		path = os.path.abspath(path)
		if self.unix:
			return path
		self._win32_load_kernel()
		if not self.GetShortPathName:
			try:
				import ctypes
				self.GetShortPathName = self.kernel32.GetShortPathNameA
				args = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32 ]
				self.GetShortPathName.argtypes = args
				self.GetShortPathName.restype = ctypes.c_uint32
			except: pass
		if not self.GetShortPathName:
			return path
		retval = self.GetShortPathName(path, self.textdata, 2048)
		shortpath = self.textdata.value
		if retval <= 0:
			import ctypes
			print 'ERROR(%d): %s'%(ctypes.GetLastError(), path)
			return ''
		return shortpath 
Example #9
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_double_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteDoubleValues.restype=ctypes.c_int32
    tecio.tecZoneVarWriteDoubleValues.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_double)) #values

    values_ptr = (ctypes.c_double*len(values))(*values)
    ret = tecio.tecZoneVarWriteDoubleValues(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_double_values Error") 
Example #10
Source File: basic.py    From lambda-packs with MIT License 6 votes vote down vote up
def c_int_array(data):
    """Get pointer of int numpy array / list."""
    if is_1d_list(data):
        data = np.array(data, copy=False)
    if is_numpy_1d_array(data):
        data = convert_from_sliced_object(data)
        assert data.flags.c_contiguous
        if data.dtype == np.int32:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_int32))
            type_data = C_API_DTYPE_INT32
        elif data.dtype == np.int64:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_int64))
            type_data = C_API_DTYPE_INT64
        else:
            raise TypeError("Expected np.int32 or np.int64, met type({})"
                            .format(data.dtype))
    else:
        raise TypeError("Unknown type({})".format(type(data).__name__))
    return (ptr_data, type_data, data)  # return `data` to avoid the temporary copy is freed 
Example #11
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_float_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteFloatValues.restype=ctypes.c_int32
    tecio.tecZoneVarWriteFloatValues.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_float)) #values

    values_ptr = (ctypes.c_float*len(values))(*values)
    ret = tecio.tecZoneVarWriteFloatValues(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_float_values Error") 
Example #12
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_int16_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteInt16Values.restype=ctypes.c_int32
    tecio.tecZoneVarWriteInt16Values.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_int16)) #values

    values_ptr = (ctypes.c_int16*len(values))(*values)
    ret = tecio.tecZoneVarWriteInt16Values(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_int16_values Error") 
Example #13
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_uint8_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteUInt8Values.restype=ctypes.c_int32
    tecio.tecZoneVarWriteUInt8Values.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_uint8)) #values

    values_ptr = (ctypes.c_uint8*len(values))(*values)
    ret = tecio.tecZoneVarWriteUInt8Values(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_uint8_values Error") 
Example #14
Source File: macos.py    From pyu2f with Apache License 2.0 6 votes vote down vote up
def GetDeviceIntProperty(dev_ref, key):
  """Reads int property from the HID device."""
  cf_key = CFStr(key)
  type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key)
  cf.CFRelease(cf_key)
  if not type_ref:
    return None

  if cf.CFGetTypeID(type_ref) != cf.CFNumberGetTypeID():
    raise errors.OsHidError('Expected number type, got {}'.format(
        cf.CFGetTypeID(type_ref)))

  out = ctypes.c_int32()
  ret = cf.CFNumberGetValue(type_ref, K_CF_NUMBER_SINT32_TYPE,
                            ctypes.byref(out))
  if not ret:
    return None

  return out.value 
Example #15
Source File: messages.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _ar_arsdk_encode_type_info(cls, ar_argtype):
        arsdk_encode_type_info_map = {
            arsdkparser.ArArgType.I8: (od.ARSDK_ARG_TYPE_I8, "i8", ctypes.c_int8),
            arsdkparser.ArArgType.U8: (od.ARSDK_ARG_TYPE_U8, "u8", ctypes.c_uint8),
            arsdkparser.ArArgType.I16: (od.ARSDK_ARG_TYPE_I16, "i16", ctypes.c_int16),
            arsdkparser.ArArgType.U16: (od.ARSDK_ARG_TYPE_U16, "u16", ctypes.c_uint16),
            arsdkparser.ArArgType.I32: (od.ARSDK_ARG_TYPE_I32, "i32", ctypes.c_int32),
            arsdkparser.ArArgType.U32: (od.ARSDK_ARG_TYPE_U32, "u32", ctypes.c_uint32),
            arsdkparser.ArArgType.I64: (od.ARSDK_ARG_TYPE_I64, "i64", ctypes.c_int64),
            arsdkparser.ArArgType.U64: (od.ARSDK_ARG_TYPE_U64, "u64", ctypes.c_uint64),
            arsdkparser.ArArgType.FLOAT: (od.ARSDK_ARG_TYPE_FLOAT, "f32", ctypes.c_float),
            arsdkparser.ArArgType.DOUBLE: (od.ARSDK_ARG_TYPE_DOUBLE, "f64", ctypes.c_double),
            arsdkparser.ArArgType.STRING: (od.ARSDK_ARG_TYPE_STRING, "cstr", od.char_pointer_cast),
            arsdkparser.ArArgType.ENUM: (od.ARSDK_ARG_TYPE_ENUM, "i32", ctypes.c_int32),
        }
        return arsdk_encode_type_info_map[ar_argtype] 
Example #16
Source File: pomp_loop_thread.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _add_fd_to_loop(self, fd, cb, fd_events, userdata=None):
        if cb is None:
            self.logger.info(
                "Cannot add fd '{}' to pomp loop without "
                "a valid callback function".format(fd)
            )
            return None
        self.fd_userdata[fd] = userdata
        userdata = ctypes.cast(
            ctypes.pointer(ctypes.py_object(userdata)), ctypes.c_void_p
        )
        self.c_fd_userdata[fd] = userdata
        self.pomp_fd_callbacks[fd] = od.pomp_fd_event_cb_t(cb)
        res = od.pomp_loop_add(
            self.pomp_loop,
            ctypes.c_int32(fd),
            od.uint32_t(int(fd_events)),
            self.pomp_fd_callbacks[fd],
            userdata
        )
        if res != 0:
            raise RuntimeError(
                "Cannot add fd '{}' to pomp loop: {} ({})".format(
                    fd, os.strerror(-res), res)
            ) 
Example #17
Source File: 371_Sum_of_Two_Integers.py    From leetcode with MIT License 6 votes vote down vote up
def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        # https://leetcode.com/discuss/111582/java-simple-easy-understand-solution-with-explanation
        # in Python this problem is much different because of the negative number
        # https://leetcode.com/discuss/111705/one-positive-one-negative-case-successful-for-python-rules
        import ctypes
        sum = 0
        carry = ctypes.c_int32(b)
        while carry.value != 0:
            sum = a ^ carry.value
            carry = ctypes.c_int32(a & carry.value)
            carry.value <<= 1
            a = sum
        return sum 
Example #18
Source File: utils.py    From debin with Apache License 2.0 6 votes vote down vote up
def adapt_int_width(n, width, signed=True):
    n = int(n)

    if width == 1:
        result = n
    elif width == 2:
        result = n
    elif width == 4:
        result = ctypes.c_int8(n).value if signed else ctypes.c_uint8(n).value
    elif width == 8:
        result = ctypes.c_int8(n).value if signed else ctypes.c_uint8(n).value
    elif width == 16:
        result = ctypes.c_int16(n).value if signed else ctypes.c_uint16(n).value
    elif width == 32:
        result = ctypes.c_int32(n).value if signed else ctypes.c_uint32(n).value
    elif width == 64:
        result = ctypes.c_int64(n).value if signed else ctypes.c_uint64(n).value
    else:
        result = n
    return result 
Example #19
Source File: quartz.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _create_font_descriptor(self, family_name, traits):
        # Create an attribute dictionary.
        attributes = c_void_p(cf.CFDictionaryCreateMutable(None, 0, cf.kCFTypeDictionaryKeyCallBacks, cf.kCFTypeDictionaryValueCallBacks))
        # Add family name to attributes.
        cfname = cocoapy.CFSTR(family_name)
        cf.CFDictionaryAddValue(attributes, cocoapy.kCTFontFamilyNameAttribute, cfname)
        cf.CFRelease(cfname)
        # Construct a CFNumber to represent the traits.
        itraits = c_int32(traits)
        symTraits = c_void_p(cf.CFNumberCreate(None, cocoapy.kCFNumberSInt32Type, byref(itraits)))
        if symTraits:
            # Construct a dictionary to hold the traits values.
            traitsDict = c_void_p(cf.CFDictionaryCreateMutable(None, 0, cf.kCFTypeDictionaryKeyCallBacks, cf.kCFTypeDictionaryValueCallBacks))
            if traitsDict:
                # Add CFNumber traits to traits dictionary.
                cf.CFDictionaryAddValue(traitsDict, cocoapy.kCTFontSymbolicTrait, symTraits)
                # Add traits dictionary to attributes.
                cf.CFDictionaryAddValue(attributes, cocoapy.kCTFontTraitsAttribute, traitsDict)
                cf.CFRelease(traitsDict)
            cf.CFRelease(symTraits)
        # Create font descriptor with attributes.
        descriptor = c_void_p(ct.CTFontDescriptorCreateWithAttributes(attributes))
        cf.CFRelease(attributes)
        return descriptor 
Example #20
Source File: darwin.py    From goreviewpartner with GNU General Public License v3.0 6 votes vote down vote up
def _set_restypes(self):
        # type: () -> None
        """ Functions return type. """

        self.core.CGGetActiveDisplayList.restype = ctypes.c_int32
        self.core.CGDisplayBounds.restype = CGRect
        self.core.CGRectStandardize.restype = CGRect
        self.core.CGRectUnion.restype = CGRect
        self.core.CGDisplayRotation.restype = ctypes.c_float
        self.core.CGWindowListCreateImage.restype = ctypes.c_void_p
        self.core.CGImageGetWidth.restype = ctypes.c_size_t
        self.core.CGImageGetHeight.restype = ctypes.c_size_t
        self.core.CGImageGetDataProvider.restype = ctypes.c_void_p
        self.core.CGDataProviderCopyData.restype = ctypes.c_void_p
        self.core.CFDataGetBytePtr.restype = ctypes.c_void_p
        self.core.CFDataGetLength.restype = ctypes.c_uint64
        self.core.CGImageGetBytesPerRow.restype = ctypes.c_size_t
        self.core.CGImageGetBitsPerPixel.restype = ctypes.c_size_t
        self.core.CGDataProviderRelease.restype = ctypes.c_void_p
        self.core.CFRelease.restype = ctypes.c_void_p 
Example #21
Source File: nao.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def init_libnao_orbs(self):
    """ Initialization of data on libnao site """
    from pyscf.nao.m_libnao import libnao
    from pyscf.nao.m_sv_chain_data import sv_chain_data
    from ctypes import POINTER, c_double, c_int64, c_int32, byref
    data = sv_chain_data(self)
    size_x = np.array([1,self.nspin,self.norbs,self.norbs,1], dtype=np.int32)
    libnao.init_sv_libnao_orbs.argtypes = (POINTER(c_double), POINTER(c_int64), POINTER(c_int32))
    libnao.init_sv_libnao_orbs(data.ctypes.data_as(POINTER(c_double)), c_int64(len(data)), size_x.ctypes.data_as(POINTER(c_int32)))
    self.init_sv_libnao_orbs = True

    libnao.init_aos_libnao.argtypes = (POINTER(c_int64), POINTER(c_int64))
    info = c_int64(-999)
    libnao.init_aos_libnao(c_int64(self.norbs), byref(info))
    if info.value!=0: raise RuntimeError("info!=0")
    return self 
Example #22
Source File: tecio_szl.py    From handyscripts with MIT License 5 votes vote down vote up
def zone_set_solution_time(file_handle, zone, solution_time, strand):
    tecio.tecZoneSetUnsteadyOptions.restype=ctypes.c_int32
    tecio.tecZoneSetUnsteadyOptions.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_double, #solutionTime
            ctypes.c_int32)  #strand

    ret = tecio.tecZoneSetUnsteadyOptions(file_handle, zone, solution_time, strand)
    if ret != 0:
        raise Exception("zone_set_solution_time Error") 
Example #23
Source File: instruction.py    From Zvm with Apache License 2.0 5 votes vote down vote up
def execute(self, frame):
        val = frame.operand_stack.pop_long()
        frame.operand_stack.push_int(ctypes.c_int32(val).value) 
Example #24
Source File: tecio.py    From handyscripts with MIT License 5 votes vote down vote up
def __zone_write_double_values(values):
    values = np.asarray(values.ravel(),dtype=np.float64)
    tecio.tecdat142.restype=ctypes.c_int32
    tecio.tecdat142.argtypes=(
            ctypes.POINTER(ctypes.c_int32), # NumPts
            ctypes.POINTER(ctypes.c_double), #values
            ctypes.POINTER(ctypes.c_int32)) #isdouble 

    isdouble = ctypes.c_int32(1)
    ret = tecio.tecdat142(
            ctypes.byref(ctypes.c_int32(len(values))),
            ctypes.cast(values.ctypes.data, ctypes.POINTER(ctypes.c_double)),
            ctypes.byref(isdouble))
    if ret != 0:
        raise Exception("zone_write_double_values Error") 
Example #25
Source File: elf.py    From vmlinux-to-elf with GNU General Public License v3.0 5 votes vote down vote up
def __new__(cls, is_big_endian = False, is_64_bits = False):
        
        actual_class = type(
            cls.__name__,
            
            (
                BigEndianStructure
                if is_big_endian
                else LittleEndianStructure,
                VariableEndiannessAndWordsizeStructure,
            ),
            
            {
                **{name: getattr(cls, name) for name in dir(cls) if '__' not in name or name == '__init__'},
                
                'is_big_endian': is_big_endian,
                'is_64_bits': is_64_bits,
            
                '_pack_': True,
                '_fields_': [
                    (
                        field[0], field[1] if is_64_bits else {
                            c_int64: c_int32,
                            c_uint64: c_uint32
                        }.get(field[1], field[1]), field[2] if len(field) > 2 else None
                    )[:3 if len(field) > 2 else 2]
                    
                    for field
                    in cls._fields_
                ]
            }
        )
        
        return actual_class() 
Example #26
Source File: test_ctypeslib.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_subarray(self):
        dt = np.dtype((np.int32, (2, 3)))
        ct = np.ctypeslib.as_ctypes_type(dt)
        assert_equal(ct, 2 * (3 * ctypes.c_int32)) 
Example #27
Source File: nnlib.py    From blueoil with Apache License 2.0 5 votes vote down vote up
def load(self, libpath):
        self.lib = ct.cdll.LoadLibrary(libpath)

        self.lib.network_create.argtypes = []
        self.lib.network_create.restype = ct.c_void_p

        self.lib.network_init.argtypes = [ct.c_void_p]
        self.lib.network_init.restype = ct.c_bool

        self.lib.network_delete.argtypes = [ct.c_void_p]
        self.lib.network_delete.restype = None

        self.lib.network_get_input_rank.argtypes = [ct.c_void_p]
        self.lib.network_get_input_rank.restype = ct.c_int

        self.lib.network_get_output_rank.argtypes = [ct.c_void_p]
        self.lib.network_get_output_rank.restype = ct.c_int

        self.lib.network_get_input_shape.argtypes = [ct.c_void_p, ndpointer(ct.c_int32, flags="C_CONTIGUOUS")]
        self.lib.network_get_input_shape.restype = None

        self.lib.network_get_output_shape.argtypes = [ct.c_void_p, ndpointer(ct.c_int32, flags="C_CONTIGUOUS")]
        self.lib.network_get_output_shape.restype = None

        self.lib.network_run.argtypes = [
            ct.c_void_p,
            ndpointer(
                ct.c_float,
                flags="C_CONTIGUOUS"),
            ndpointer(
                ct.c_float,
                flags="C_CONTIGUOUS"),
        ]
        self.lib.network_run.restype = None

        self.nnlib = self.lib.network_create()
        return True 
Example #28
Source File: nnlib.py    From blueoil with Apache License 2.0 5 votes vote down vote up
def load(self, libpath):
        self.lib = ct.cdll.LoadLibrary(libpath)

        self.lib.network_create.argtypes = []
        self.lib.network_create.restype = ct.c_void_p

        self.lib.network_init.argtypes = [ct.c_void_p]
        self.lib.network_init.restype = ct.c_bool

        self.lib.network_delete.argtypes = [ct.c_void_p]
        self.lib.network_delete.restype = None

        self.lib.network_get_input_rank.argtypes = [ct.c_void_p]
        self.lib.network_get_input_rank.restype = ct.c_int

        self.lib.network_get_output_rank.argtypes = [ct.c_void_p]
        self.lib.network_get_output_rank.restype = ct.c_int

        self.lib.network_get_input_shape.argtypes = [ct.c_void_p, ndpointer(ct.c_int32, flags="C_CONTIGUOUS")]
        self.lib.network_get_input_shape.restype = None

        self.lib.network_get_output_shape.argtypes = [ct.c_void_p, ndpointer(ct.c_int32, flags="C_CONTIGUOUS")]
        self.lib.network_get_output_shape.restype = None

        self.lib.network_run.argtypes = [
            ct.c_void_p,
            ndpointer(
                ct.c_float,
                flags="C_CONTIGUOUS"),
            ndpointer(
                ct.c_float,
                flags="C_CONTIGUOUS"),
        ]
        self.lib.network_run.restype = None

        self.nnlib = self.lib.network_create()
        return True 
Example #29
Source File: debuginfo.py    From debin with Apache License 2.0 5 votes vote down vote up
def get_array_upper_bound(self, die):
        for child in die.iter_children():
            if child.tag == 'DW_TAG_subrange_type':
                upper_bound_attr = child.attributes.get('DW_AT_upper_bound', None)
                if upper_bound_attr is None:
                    return None
                else:
                    if upper_bound_attr.form in ('DW_FORM_data1',
                                                 'DW_FORM_data2',
                                                 'DW_FORM_data4',
                                                 'DW_FORM_data8'):
                        return upper_bound_attr.value
                    elif upper_bound_attr.form == 'DW_FORM_exprloc':
                        loc = upper_bound_attr.value
                        if loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1u']:
                            return ctypes.c_uint8(loc[1]).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1s']:
                            return ctypes.c_int8(loc[1]).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2u']:
                            return ctypes.c_uint16(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2s']:
                            return ctypes.c_int16(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4u']:
                            return ctypes.c_uint32(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4s']:
                            return ctypes.c_int32(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8u']:
                            return ctypes.c_uint64(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8s']:
                            return ctypes.c_int64(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_constu']:
                            return utils.decode_uleb128(loc[1:])
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_consts']:
                            return utils.decode_sleb128(loc[1:])
                        else:
                            return None
                    else:
                        return None 
Example #30
Source File: common.py    From MobulaOP with MIT License 5 votes vote down vote up
def _get_numpy_type():
        name2ctype = dict()
        pairs = [
            (np.dtype('int8'), ctypes.c_int8),
            (np.dtype('int16'), ctypes.c_int16),
            (np.dtype('int32'), ctypes.c_int32),
            (np.dtype('int64'), ctypes.c_int64),  # alias: np.int
            (np.dtype('float32'), ctypes.c_float),
            (np.dtype('float64'), ctypes.c_double),  # alias: np.float
        ]
        for dtype, ctype in pairs:
            name2ctype[dtype.name] = ctype
        return name2ctype