예제 #1
0
def SEPIA2_FWR_GetLastError(iDevIdx): 
	piErrCode = 0
	piPhase = 0
	piLocation = 0
	piSlot = 0
	cCondition = " "	
	INTP = ctypes.POINTER(ctypes.c_int)  
	SEPIA2_FWR_GetLastError_Proto = ctypes.WINFUNCTYPE(ctypes.c_int,ctypes.c_int,INTP,INTP,INTP,INTP,ctypes.c_char_p)
	SEPIA2_FWR_GetLastError_Params = (1,"p1",0),(1,"p2",0),(1,"p3",0),(1,"p4",0),(1,"p5",0),(1,"p6",0),
	SEPIA2_FWR_GetLastError_API = SEPIA2_FWR_GetLastError_Proto(("SEPIA2_FWR_GetLastError",sepiadll),SEPIA2_FWR_GetLastError_Params)
	
	p1 = ctypes.c_int(iDevIdx)
	
	num2 = ctypes.c_int(piErrCode)
	addr2 = ctypes.addressof(num2)
	p2 = ctypes.cast(addr2, INTP)  

	num3 = ctypes.c_int(piPhase)	
	addr3 = ctypes.addressof(num3)
	p3 = ctypes.cast(addr3, INTP)  

	num4 = ctypes.c_int(piLocation)	
	addr4 = ctypes.addressof(num4)
	p4 = ctypes.cast(addr4, INTP)  

	num5 = ctypes.c_int(piSlot)	
	addr5 = ctypes.addressof(num5)
	p5 = ctypes.cast(addr5, INTP)  

	p6 = ctypes.c_char_p(cCondition)  
		
	iRetVal = SEPIA2_FWR_GetLastError_API(p1,p2,p3,p4,p5,p6)

	print 'PYSEPIA::Error ' + str(p2.contents)
예제 #2
0
파일: wpk.py 프로젝트: jianglu/v8monkey
def get_pids(process_name):
    BIG_ARRAY = DWORD * 4096
    processes = BIG_ARRAY()
    needed = DWORD()

    pids = []
    result = windll.psapi.EnumProcesses(processes, sizeof(processes), addressof(needed))
    if not result:
        return pids

    num_results = needed.value / sizeof(DWORD)

    for i in range(num_results):
        pid = processes[i]
        process = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid)
        if process:
            module = HANDLE()
            result = windll.psapi.EnumProcessModules(process, addressof(module), sizeof(module), addressof(needed))
            if result:
                name = create_unicode_buffer(1024)
                result = windll.psapi.GetModuleBaseNameW(process, module, name, len(name))
                # TODO: This might not be the best way to
                # match a process name; maybe use a regexp instead.
                if name.value.startswith(process_name):
                    pids.append(pid)
                windll.kernel32.CloseHandle(module)
            windll.kernel32.CloseHandle(process)

    return pids
예제 #3
0
        def list_base_iter(self, type_name):
            if type(type_name) == str:
                type_cast = struct_dict[type_name.encode('ASCII')]
            else:
                # allow passing types direcly
                type_cast = type_name

            # empty listbase
            if self.first is None:
                ret = None
            else:
                try:
                    ret = type_cast_link.from_address(ctypes.addressof(self.first))
                except TypeError:
                    ret = type_cast_link.from_address(self.first)

            while ret is not None:
                return_value = type_cast.from_address(ctypes.addressof(ret))
                try:
                    next_pointer = getattr(ret.next, "contents")
                except:
                    next_pointer = None

                if next_pointer:
                    ret = type_cast_link.from_address(ctypes.addressof(next_pointer))
                else:
                    ret = None

                yield return_value
예제 #4
0
 def create(data):
     'Create a transfer from given 3 byte list data'
     wbuf = ctypes.create_string_buffer(struct.pack('3B', *data))
     rbuf = ctypes.create_string_buffer(3)
     sptr = struct.pack('QQLLHBBL', ctypes.addressof(wbuf),
             ctypes.addressof(rbuf), 3, 0, 0, 0, 0, 0)
     return ctypes.create_string_buffer(sptr), wbuf, rbuf
    def _readSMART(self, name):
        serial = 'NO SERIAL NUMBER'
        handle = ctypes.windll.kernel32.CreateFileW(
            name,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
            None, win32file.OPEN_EXISTING, 0, 0)
        if handle == -1:
            logging.warning("Failed to open device '%s' for querying the "
                            "serial number. Error code: %d", name,
                            win32api.GetLastError())
            return serial
        q = StoragePropertyQuery()
        r = StorageDeviceDescriptor()
        read_count = ctypes.wintypes.ULONG()
        ret = ctypes.windll.kernel32.DeviceIoControl(
            handle, 0x002D1400, ctypes.addressof(q), ctypes.sizeof(q),
            ctypes.addressof(r), ctypes.sizeof(r),
            ctypes.addressof(read_count), 0)

        if ret:
            serial = buffer(r)[r.SerialNumberOffset:r.SerialNumberOffset + 20]
        else:
            logging.warning("DeviceIoControl for device %s failed with"
                            "eror code: %d. Could not look up serial number",
                            name, win32api.GetLastError())
        ctypes.windll.kernel32.CloseHandle(handle)
        return serial
예제 #6
0
    def __init__(self):
        logsz = int(os.environ.get('NUMBAPRO_CUDA_LOG_SIZE', 1024))
        linkerinfo = (c_char * logsz)()
        linkererrors = (c_char * logsz)()

        options = {
            enums.CU_JIT_INFO_LOG_BUFFER: addressof(linkerinfo),
            enums.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
            enums.CU_JIT_ERROR_LOG_BUFFER: addressof(linkererrors),
            enums.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
            enums.CU_JIT_LOG_VERBOSE: c_void_p(1),
        }

        raw_keys = list(options.keys()) + [enums.CU_JIT_TARGET_FROM_CUCONTEXT]
        raw_values = list(options.values())
        del options

        option_keys = (drvapi.cu_jit_option * len(raw_keys))(*raw_keys)
        option_vals = (c_void_p * len(raw_values))(*raw_values)

        self.handle = handle = drvapi.cu_link_state()
        driver.cuLinkCreate(len(raw_keys), option_keys, option_vals,
                            byref(self.handle))

        self.finalizer = lambda: driver.cuLinkDestroy(handle)

        self.linker_info_buf = linkerinfo
        self.linker_errors_buf = linkererrors

        self._keep_alive = [linkerinfo, linkererrors, option_keys, option_vals]
예제 #7
0
def load_module_image(context, image):
    """
    image must be a pointer
    """
    logsz = os.environ.get('NUMBAPRO_CUDA_LOG_SIZE', 1024)

    jitinfo = (c_char * logsz)()
    jiterrors = (c_char * logsz)()

    options = {
        enums.CU_JIT_INFO_LOG_BUFFER: addressof(jitinfo),
        enums.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
        enums.CU_JIT_ERROR_LOG_BUFFER: addressof(jiterrors),
        enums.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
        enums.CU_JIT_LOG_VERBOSE: c_void_p(VERBOSE_JIT_LOG),
    }

    option_keys = (drvapi.cu_jit_option * len(options))(*options.keys())
    option_vals = (c_void_p * len(options))(*options.values())

    handle = drvapi.cu_module()
    try:
        driver.cuModuleLoadDataEx(byref(handle), image, len(options),
                                  option_keys, option_vals)
    except CudaAPIError as e:
        msg = "cuModuleLoadDataEx error:\n%s" % jiterrors.value.decode("utf8")
        raise CudaAPIError(e.code, msg)

    info_log = jitinfo.value

    return Module(weakref.proxy(context), handle, info_log,
                  _module_finalizer(context, handle))
예제 #8
0
def test_from_ctypes():
    
    for type, dtype in [(ctypes.c_int16, 'int16'), 
                        (ctypes.c_uint8, 'uint8'), 
                        (ctypes.c_float, 'float32'), 
                        (ctypes.c_double, 'float64')]:
        # Create ctypes array, possibly something that we get from a c lib
        buffer = (type*100)()
        
        # Create array!
        b = tnp.ndarray((4, 25), dtype, buffer=buffer)
        
        # Check that we can turn it into a numpy array
        a = np.array(b, copy=False)
        assert (a == b).all()
        assert a.dtype == dtype
        
        # Verify that both point to the same data
        assert a.__array_interface__['data'][0] == ctypes.addressof(buffer)
        assert b.__array_interface__['data'][0] == ctypes.addressof(buffer)
        
        # also verify offset in __array_interface__ here
        for a0, b0 in zip([a[2:], a[:, 10::2], a[1::2, 10:20:2]],
                          [b[2:], b[:, 10::2], b[1::2, 10:20:2]]):
            pa = a0.__array_interface__['data'][0]
            pb = b0.__array_interface__['data'][0]
            assert pa > ctypes.addressof(buffer)
            assert pa == pb
예제 #9
0
파일: pf.py 프로젝트: luserx0/sshuttle
    def query_nat(self, family, proto, src_ip, src_port, dst_ip, dst_port):
        [proto, family, src_port, dst_port] = [
            int(v) for v in [proto, family, src_port, dst_port]]

        packed_src_ip = socket.inet_pton(family, src_ip)
        packed_dst_ip = socket.inet_pton(family, dst_ip)

        assert len(packed_src_ip) == len(packed_dst_ip)
        length = len(packed_src_ip)

        pnl = self.pfioc_natlook()
        pnl.proto = proto
        pnl.direction = self.PF_OUT
        pnl.af = family
        memmove(addressof(pnl.saddr), packed_src_ip, length)
        memmove(addressof(pnl.daddr), packed_dst_ip, length)
        self._add_natlook_ports(pnl, src_port, dst_port)

        ioctl(pf_get_dev(), self.DIOCNATLOOK,
              (c_char * sizeof(pnl)).from_address(addressof(pnl)))

        ip = socket.inet_ntop(
            pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw)
        port = socket.ntohs(self._get_natlook_port(pnl.rdxport))
        return (ip, port)
예제 #10
0
    def transaction(self, bytes_to_send):
        """Sends bytes via the SPI bus.

        :param bytes_to_send: The bytes to send on the SPI device.
        :type bytes_to_send: bytes
        :returns: bytes -- returned bytes from SPI device
        :raises: InitError
        """
        bytes_to_send = _pybytes(bytes_to_send)

        # make some buffer space to store reading/writing
        wbuffer = ctypes.create_string_buffer(bytes_to_send,
                                              len(bytes_to_send))
        rbuffer = ctypes.create_string_buffer(len(bytes_to_send))

        # create the spi transfer struct
        transfer = spi_ioc_transfer(
            tx_buf=ctypes.addressof(wbuffer),
            rx_buf=ctypes.addressof(rbuffer),
            len=ctypes.sizeof(wbuffer))

        if self.spi_transaction_callback is not None:
            self.spi_transaction_callback(bytes_to_send)

        # send the spi command
        ioctl(self.fd, SPI_IOC_MESSAGE(1), transfer)
        return _pyord(ctypes.string_at(rbuffer, ctypes.sizeof(rbuffer)))
예제 #11
0
def nn_send(socket, msg, flags):
    "send a message"
    try:
        return _nn_send(socket, ctypes.addressof(msg), len(buffer(msg)), flags)
    except (TypeError, AttributeError):
        buf_msg = ctypes.create_string_buffer(msg)
        return _nn_send(socket, ctypes.addressof(buf_msg), len(msg), flags)
예제 #12
0
 def test_assignment_ckernel(self):
     ckd = _lowlevel.make_ckernel_deferred_from_assignment(
                 ndt.float32, ndt.int64,
                 "unary", "none")
     self.assertEqual(nd.as_py(ckd.types), [ndt.float32, ndt.int64])
     # Instantiate as a single kernel
     with _lowlevel.ckernel.CKernelBuilder() as ckb:
         meta = (ctypes.c_void_p * 2)()
         _lowlevel.ckernel_deferred_instantiate(ckd, ckb, 0, meta, "single")
         ck = ckb.ckernel(_lowlevel.UnarySingleOperation)
         # Do an assignment using ctypes
         i64 = ctypes.c_int64(1234)
         f32 = ctypes.c_float(1)
         ck(ctypes.addressof(f32), ctypes.addressof(i64))
         self.assertEqual(f32.value, 1234.0)
     # Instantiate as a strided kernel
     with _lowlevel.ckernel.CKernelBuilder() as ckb:
         meta = (ctypes.c_void_p * 2)()
         _lowlevel.ckernel_deferred_instantiate(ckd, ckb, 0, meta, "strided")
         ck = ckb.ckernel(_lowlevel.UnaryStridedOperation)
         # Do an assignment using ctypes
         i64 = (ctypes.c_int64 * 3)()
         for i, v in enumerate([3,7,21]):
             i64[i] = v
         f32 = (ctypes.c_float * 3)()
         ck(ctypes.addressof(f32), 4,
                     ctypes.addressof(i64), 8,
                     3)
         self.assertEqual([f32[i] for i in range(3)], [3,7,21])
예제 #13
0
def DerefPointer(pointer, processID):
#	print 'POINTER!!!!! %s, pointer points to address (/has value): %s (%s)' % (type(pointer.contents), ctypes.addressof(pointer.contents), hex(ctypes.addressof(pointer.contents)))
#	res = []
#	res.append('%s = %r' % (fieldName, pointer))
#	res.append('\n')

	try:
#		ctypes.addressof(value.contents)
		if ctypes.addressof(pointer.contents) != 0:
#		if bool(pointer.contents):
	#		contents = pointer.contents
			pointedAtType = type(pointer.contents)
			typeInstanceInLocalMem = pointedAtType()
			contents = ReadMem(ctypes.addressof(pointer.contents), ctypes.sizeof(pointer.contents), None, processID)

			fit = min(len(contents), ctypes.sizeof(typeInstanceInLocalMem))

			# Copy 
			ctypes.memmove(ctypes.addressof(typeInstanceInLocalMem), contents, fit)

			return typeInstanceInLocalMem

			return contents
		else:
			return None
	except:
		pass
	return None
예제 #14
0
파일: ffi.py 프로젝트: bitcraft/pyglet
    def __getattr__(self, name):
        kind, value = self.map[name]
        if kind == 'constant':
            result = value
        elif kind == 'typedef':
            result = self.get_type(value)
        elif kind == 'enum':
            result = self.get_enum_type(name, value)
        elif kind == 'struct':
            result = self.get_class_type(name, value, c.Structure)
        elif kind == 'union':
            result = self.get_class_type(name, value, c.Union)
        elif kind == 'function':
            address = c.addressof(getattr(self.lib, name))
            result_type = self.get_type(value)
            result = result_type.from_address(address)
        elif kind == 'variable':
            address = c.addressof(getattr(self.lib, name))
            result_type = self.get_type(value)
            result = result_type.from_address(address)
        else:
            raise RuntimeError(kind)

        setattr(self, name, result)
        return result
 def testWlanGetProfileSuccess(self):
     handle = WlanOpenHandle()
     wlan_ifaces = WlanEnumInterfaces(handle)
     data_type = wlan_ifaces.contents.InterfaceInfo._type_
     num = wlan_ifaces.contents.NumberOfItems
     ifaces_pointer = addressof(wlan_ifaces.contents.InterfaceInfo)
     wlan_iface_info_list = (data_type * num).from_address(ifaces_pointer)
     msg = "We expect at least one wireless interface."
     self.assertGreaterEqual(len(wlan_iface_info_list), 0, msg)
     for wlan_iface_info in wlan_iface_info_list:
         iface_guid = wlan_iface_info.InterfaceGuid
         profile_list = WlanGetProfileList(handle, iface_guid)
         data_type = profile_list.contents.ProfileInfo._type_
         num = profile_list.contents.NumberOfItems
         profile_info_pointer = addressof(profile_list.contents.ProfileInfo)
         profiles_list = (data_type * num).from_address(profile_info_pointer)
         msg = "We expect at least one profile info."
         self.assertGreater(profile_list.contents.NumberOfItems, 0, msg)
         for profile in profiles_list:
             xml_data = WlanGetProfile(handle,
                                       wlan_iface_info.InterfaceGuid,
                                       profile.ProfileName)
             msg = "We expect a string of at least 20 bytes."
             self.assertGreater(len(xml_data.value), 20, msg)
     WlanFreeMemory(wlan_ifaces)
     WlanCloseHandle(handle)
예제 #16
0
def _readListViewItems(hwnd, column_index=0):
    # Allocate virtual memory inside target process
    pid = ctypes.create_string_buffer(4)
    p_pid = ctypes.addressof(pid)
    GetWindowThreadProcessId(hwnd, p_pid)  # process owning the given hwnd
    hProcHnd = OpenProcess(win32con.PROCESS_ALL_ACCESS, False, struct.unpack("i", pid)[0])
    pLVI = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE)
    pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE)

    # Prepare an LVITEM record and write it to target process memory
    lvitem_str = struct.pack('iiiiiiiii', *[0, 0, column_index, 0, 0, pBuffer, 4096, 0, 0])
    lvitem_buffer = ctypes.create_string_buffer(lvitem_str)
    copied = ctypes.create_string_buffer(4)
    p_copied = ctypes.addressof(copied)
    WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied)

    # iterate items in the SysListView32 control
    num_items = win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMCOUNT)
    item_texts = []
    for item_index in range(num_items):
        win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMTEXT, item_index, pLVI)
        target_buff = ctypes.create_string_buffer(4096)
        ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied)
        item_texts.append(target_buff.value)

    VirtualFreeEx(hProcHnd, pBuffer, 0, win32con.MEM_RELEASE)
    VirtualFreeEx(hProcHnd, pLVI, 0, win32con.MEM_RELEASE)
    win32api.CloseHandle(hProcHnd)
    return item_texts
예제 #17
0
    def transfer(self, data, speed=0, bits_per_word=0, delay=0):
        """Perform full-duplex Spi transfer

        Args:
            data: List of words to transmit
            speed: Optional temporary bitrate override in Hz. 0 (default)
                uses existing spidev speed setting.
            bits_per_word: Optional temporary bits_per_word override. 0
                (default) will use the current bits_per_word setting.
            delay: Optional delay in usecs between sending the last bit and
                deselecting the chip select line. 0 (default) for no delay.

        Returns:
            List of words read from Spi bus during transfer
        """
        data = array.array('B', data).tostring()
        length = len(data)
        transmit_buffer = ctypes.create_string_buffer(data)
        receive_buffer = ctypes.create_string_buffer(length)
        spi_ioc_transfer = struct.pack(Spi._IOC_TRANSFER_FORMAT,
                                       ctypes.addressof(transmit_buffer),
                                       ctypes.addressof(receive_buffer),
                                       length, speed, delay, bits_per_word, 0,
                                       0, 0, 0)
        fcntl.ioctl(self.handle, Spi._IOC_MESSAGE, spi_ioc_transfer)
        return [ord(byte) for byte in ctypes.string_at(receive_buffer, length)]
예제 #18
0
 def open_selector(func, title, filters = [('All Files', ('*.*',))], 
                   root = '', multi = False):
     ofx = OPENFILENAME(0, title, multi)
     lpstrFile = create_unicode_buffer(root, 1024)
     ofx.lpstrFile = cast(lpstrFile, c_wchar_p)
     newFilters = []
     for filter in filters:
         filterTypes = ';'.join(filter[1])
         newFilters.append('%s (%s)' % (filter[0], filterTypes))
         newFilters.append(filterTypes)
     filterText = '\x00'.join(newFilters) + "\x00\x00"
     ofx.lpstrFilter = filterText
     print 'doing it'
     if func(ctypes.byref(ofx)):
         if multi:
             '%r' % ofx.lpstrFile
             print string_at(addressof(lpstrFile), 1024)
             offset = addressof(lpstrFile)
             print offset
             items = []
             while 1:
                 item = wstring_at(offset)
                 offset += len(item)
                 if item == '':
                     break
                 items.append(item)
             return items
         else:
             return ofx.lpstrFile.replace("\0", "")
     return ''
예제 #19
0
	def testUserSuppliedHash( self ) :

		with IECoreArnold.UniverseBlock( writable = True ) :

			c = IECoreArnold.InstancingConverter()

			m1 = IECore.MeshPrimitive.createPlane( IECore.Box2f( IECore.V2f( -1 ), IECore.V2f( 1 ) ) )
			m2 = IECore.MeshPrimitive.createPlane( IECore.Box2f( IECore.V2f( -2 ), IECore.V2f( 2 ) ) )

			h1 = IECore.MurmurHash()
			h2 = IECore.MurmurHash()

			h1.append( 10 )
			h2.append( 10 )

			am1a = c.convert( m1, h1 )
			self.assertEqual( arnold.AiNodeEntryGetName( arnold.AiNodeGetNodeEntry( am1a ) ), "polymesh" )
			am1b = c.convert( m1, h1 )
			self.assertEqual( arnold.AiNodeEntryGetName( arnold.AiNodeGetNodeEntry( am1b ) ), "ginstance" )
			self.assertEqual( arnold.AiNodeGetPtr( am1b, "node" ), ctypes.addressof( am1a.contents ) )

			am2a = c.convert( m2, h2 )
			self.assertEqual( arnold.AiNodeEntryGetName( arnold.AiNodeGetNodeEntry( am2a ) ), "polymesh" )
			am2b = c.convert( m2, h2 )
			self.assertEqual( arnold.AiNodeEntryGetName( arnold.AiNodeGetNodeEntry( am2b ) ), "ginstance" )
			self.assertEqual( arnold.AiNodeGetPtr( am2b, "node" ), ctypes.addressof( am2a.contents ) )
예제 #20
0
    def compress(self, counts_limit):
        '''Compress this payload instance
        Args:
            counts_limit how many counters should be encoded
                           starting from index 0 (can be 0),
        Return:
            the compressed payload (python string)
        '''
        if self.payload:
            # worst case varint encoded length is when each counter is at the maximum value
            # in this case 1 more byte per counter is needed due to the more bits
            varint_len = counts_limit * (self.word_size + 1)
            # allocate enough space to fit the header and the varint string
            encode_buf = (c_byte * (payload_header_size + varint_len))()

            # encode past the payload header
            varint_len = encode(addressof(self.counts), counts_limit,
                                self.word_size,
                                addressof(encode_buf) + payload_header_size,
                                varint_len)

            # copy the header after updating the varint stream length
            self.payload.payload_len = varint_len
            ctypes.memmove(addressof(encode_buf), addressof(self.payload), payload_header_size)

            cdata = zlib.compress(ctypes.string_at(encode_buf, payload_header_size + varint_len))
            return cdata
        # can't compress if no payload
        raise RuntimeError('No payload to compress')
예제 #21
0
 def test_array_from_ptr(self):
     # cfixed_dim arrmeta is redundant so this is ok
     a = (ctypes.c_int32 * 3)()
     a[0] = 3
     a[1] = 6
     a[2] = 9
     # Readwrite version using cfixed
     b = _lowlevel.array_from_ptr('cfixed[3] * int32',
                                  ctypes.addressof(a), a, 'readwrite')
     self.assertEqual(_lowlevel.data_address_of(b), ctypes.addressof(a))
     self.assertEqual(nd.dshape_of(b), '3 * int32')
     self.assertEqual(nd.as_py(b), [3, 6, 9])
     b[1] = 10
     self.assertEqual(a[1], 10)
     # Readonly version using cfixed
     b = _lowlevel.array_from_ptr('cfixed[3] * int32',
                                  ctypes.addressof(a), a, 'readonly')
     self.assertEqual(nd.as_py(b), [3, 10, 9])
     def assign_to(b):
         b[1] = 100
     self.assertRaises(RuntimeError, assign_to, b)
     # Using a fixed dim default-constructs the arrmeta, so works too
     b = _lowlevel.array_from_ptr('3 * int32', ctypes.addressof(a),
                                  a, 'readonly')
     self.assertEqual(nd.as_py(b), [3, 10, 9])
     # Should get an error if we try strided, because the size is unknown
     self.assertRaises(RuntimeError,
                       lambda: _lowlevel.array_from_ptr('strided * int32',
                                                        ctypes.addressof(a),
                                                        a, 'readonly'))
예제 #22
0
파일: atom.py 프로젝트: JesseMaurais/Pyxie
def GetProperty(window, property, type=XA.ANY, delete=False):
	'Auto convert GetWindowProperty result to its type'

	format = 32
	items = 1
	length = 1
	bytes = None
	data = None

	while length:
		type, format, items, length, bytes = window.GetWindowProperty(
			property, 0, length, delete, type
			)
			
	if type.value in PropertyType:
		data = PropertyType[type.value]()
	else:
		if format == 32:
			data = (X.CARD32 * nitems)()
		if format == 16:
			data = (X.CARD16 * nitems)()
		if format ==  8:
			data = (X.CARD8  * nitems)()

	from ctypes import sizeof, addressof, memmove
	memmove(addressof(data), addressof(bytes), sizeof(data))

	return data
예제 #23
0
파일: types.py 프로젝트: coryo/python-mpv
 def set(self, dst, src):
     src_t = type(src)
     if src_t is str:
         dst.format.value = Format.STRING
         dst.string = src.encode()
     elif src_t is bool:
         dst.format.value = Format.FLAG
         dst.flag = int(src)
     elif src_t is int:
         dst.format.value = Format.INT64
         dst.int64 = src
     elif src_t is float:
         dst.format.value = Format.DOUBLE
         dst.double_ = src
     elif src_t in (list, tuple):
         l = MpvNodeList(False, len(src))
         self.node._heap.append(l)
         dst.format.value = Format.NODE_ARRAY
         dst.list = cast(addressof(l), POINTER(MpvNodeList))
         for i, item in enumerate(src):
             self.set(dst.list.contents.values[i], item)
     elif src_t is dict:
         l = MpvNodeList(True, len(src))
         self.node._heap.append(l)
         dst.format.value = Format.NODE_MAP
         dst.list = cast(addressof(l), POINTER(MpvNodeList))
         for i, (k, v) in enumerate(src.items()):
             if type(k) is not str:
                 raise KeyError('Dict keys must be strings.')
             dst.list.contents.keys[i] = k.encode()
             self.set(dst.list.contents.values[i], v)
     else:
         raise TypeError('Unsupported type for a Node.')
예제 #24
0
    def open_selector(func, title, filters = [('All Files', ('*.*',))], 
                      root = '', multi = False):
        ofx = OPENFILENAME(0, title, multi)
        lpstrFile = create_unicode_buffer(root, 1024)
        ofx.lpstrFile = cast(lpstrFile, c_wchar_p)
        newFilters = []
        for filter in filters:
            filterTypes = ';'.join(filter[1])
            newFilters.append('%s (%s)' % (filter[0], filterTypes))
            newFilters.append(filterTypes)
        filterText = '\x00'.join(newFilters) + "\x00\x00"
        ofx.lpstrFilter = filterText
        if func(ctypes.byref(ofx)):
            if multi:
                offset = addressof(lpstrFile)
                items = []
                while 1:
                    item = wstring_at(offset)
                    offset += (len(item) + 1) * 2
                    if item == '':
                        break
                    items.append(item)

                if len(items) == 1:
                    return items
                directory = items[0]
                new_items = []
                for item in items[1:]:
                    new_items.append(os.path.join(directory, item))
                return new_items
            else:
                return wstring_at(addressof(lpstrFile))
        return ''
예제 #25
0
파일: spi.py 프로젝트: Hunter275/webiopi
 def xfer(self, txbuff=None):
     length = len(txbuff)
     if PYTHON_MAJOR >= 3:
         _txbuff = bytes(txbuff)
         _txptr = ctypes.create_string_buffer(_txbuff)
     else:
         _txbuff = str(bytearray(txbuff))
         _txptr = ctypes.create_string_buffer(_txbuff)
     _rxptr = ctypes.create_string_buffer(length)
     
     data = struct.pack("QQLLHBBL",  #64 64 32 32 16 8 8 32 b = 32B
                 ctypes.addressof(_txptr),
                 ctypes.addressof(_rxptr),
                 length,
                 self.speed,
                 0, #delay
                 self.bits,
                 0, # cs_change,
                 0  # pad
                 )
     
     fcntl.ioctl(self.fd, SPI_IOC_MESSAGE(len(data)), data)
     _rxbuff = ctypes.string_at(_rxptr, length)
     return bytearray(_rxbuff)
     
예제 #26
0
    def wait(self):
        """Wait until the associated xseg_request is responded, discarding any
        other requests that may be received in the meantime"""
        while True:
            received = xseg_receive(self.xseg_ctx.ctx, self.xseg_ctx.portno, 0)
            if received:
#                print addressof(cast(self.req, c_void_p))
#                print addressof(cast(received, c_void_p))
#                print addressof(self.req.contents)
#                print addressof(received.contents)
                if addressof(received.contents) == \
                        addressof(self.req.contents):
#                if addressof(cast(received, c_void_p)) == \
#                        addressof(cast(self.req, c_void_p)):
                    break
                else:
                    p = xseg_respond(self.xseg_ctx.ctx, received,
                                     self.xseg_ctx.portno, X_ALLOC)
                    if p == NoPort:
                        xseg_put_request(self.xseg_ctx.ctx, received,
                                         self.xseg_ctx.portno)
                    else:
                        xseg_signal(self.xseg_ctx.ctx, p)
            else:
                xseg_prepare_wait(self.xseg_ctx.ctx, self.xseg_ctx.portno)
                xseg_wait_signal(self.xseg_ctx.ctx, 10000000)
                xseg_cancel_wait(self.xseg_ctx.ctx, self.xseg_ctx.portno)
        return True
예제 #27
0
파일: core.py 프로젝트: prodigeni/kplugs
	def __call__(self, func, *args):
		if not func in self.funcs:
			raise Exception("This function doesn't belongs to this plug")

		if func.anonymous:
			op = Plug.KPLUGS_EXECUTE_ANONYMOUS
			length = 0
			ptr = func.addr
		else:
			op = Plug.KPLUGS_EXECUTE
			length = len(func.name)
			name_buf = ctypes.c_buffer(func.name)
			ptr = ctypes.addressof(name_buf)

		new_args = []
		bufs = []
		for arg in args:
			add = arg
			if isinstance(arg, str):
				bufs.append(ctypes.c_buffer(arg))
				add = ctypes.addressof(bufs[-1])
			new_args.append(add)
		args_buf = ctypes.c_buffer(struct.pack("P" * len(new_args), *new_args))

		# send the command (will throw an exception if it fails)
		return self._exec_cmd(op, length, len(args) * WORD_SIZE, ptr, ctypes.addressof(args_buf))
예제 #28
0
    def _sim(self, s1, s2, func) :
        end, ret = self.get_in_rcaches( s1, s2 )
        if end != -1 :
            return end, ret
#-----	
	#print "lolll"
        self.__libsim_t.orig = cast( s1, c_void_p )
        self.__libsim_t.size_orig = len(s1)

        self.__libsim_t.cmp = cast( s2, c_void_p )
        self.__libsim_t.size_cmp = len(s2)

        corig = self.get_in_caches(s1)
        ccmp = self.get_in_caches(s2)
        
        self.__libsim_t.corig = addressof( corig )
        self.__libsim_t.ccmp = addressof( ccmp )

        ret = func( self.level, addressof( self.__libsim_t ) )

        self.add_in_caches(s1, corig)
        self.add_in_caches(s2, ccmp)
        self.add_in_rcaches(s1+s2, self.__libsim_t.res, ret)

        return self.__libsim_t.res, ret
예제 #29
0
파일: fusell.py 프로젝트: rianhunter/fusepy
    def reply_readdir(self, req, size, off, entries):
        bufsize = 0
        sized_entries = []
        for name, attr in entries:
            name = name.encode(self.encoding)
            entsize = self.libfuse.fuse_add_direntry(req, None, 0, name, None, 0)
            sized_entries.append((name, attr, entsize))
            bufsize += entsize

        next = 0
        buf = ctypes.create_string_buffer(bufsize)
        for name, attr, entsize in sized_entries:
            entbuf = ctypes.cast(
                ctypes.addressof(buf) + next, ctypes.c_char_p)
            st = c_stat(**attr)
            next += entsize
            self.libfuse.fuse_add_direntry(
                req, entbuf, entsize, name, ctypes.byref(st), next)

        if off < bufsize:
            buf = ctypes.cast(
                ctypes.addressof(buf) + off, ctypes.c_char_p) if off else buf
            return self.libfuse.fuse_reply_buf(req, buf, min(bufsize - off, size))
        else:
            return self.libfuse.fuse_reply_buf(req, None, 0)
    def notifyMaterialSetup(self, pass_id, mat):
        ## Prepare the fragment params offsets
#       switch(pass_id)
#       ##case 994: ## rt_lum4
#       if pass_id ==  993: ## rt_lum3
#       case 992: ## rt_lum2
#       case 991: ## rt_lum1
#       case 990: ## rt_lum0
#           break 
#       case 800: ## rt_brightpass
#           break 
        
        if pass_id == 701: ## rt_bloom1
                ## horizontal bloom
                mat.load() 
                fparams = mat.getBestTechnique().getPass(0).getFragmentProgramParameters() 
                progName = mat.getBestTechnique().getPass(0).getFragmentProgramName() 
                fparams.setNamedConstantFloat("sampleOffsets",ctypes.addressof(self.mBloomTexOffsetsHorz), self.x) 
                fparams.setNamedConstantFloat("sampleWeights",ctypes.addressof(self.mBloomTexWeights), self.x) 
        elif pass_id == 700: ## rt_bloom0
                ## vertical bloom
                mat.load() 
                fparams = mat.getTechnique(0).getPass(0).getFragmentProgramParameters() 
                progName = mat.getBestTechnique().getPass(0).getFragmentProgramName() 
                fparams.setNamedConstantFloat("sampleOffsets",ctypes.addressof(self.mBloomTexOffsetsVert), self.x) 
                fparams.setNamedConstantFloat("sampleWeights",ctypes.addressof(self.mBloomTexWeights), self.x) 
예제 #31
0
def customResize(array, newSize):
    return (array._type_ * newSize).from_address(addressof(array))
예제 #32
0
 def next(self):
     if not self.NextEntryOffset:
         return None
     return type(self).from_address(ctypes.addressof(self) + self.NextEntryOffset)
예제 #33
0
 def name(self):
     return gdef.LPWSTR(ctypes.addressof(self) + type(self).StreamName.offset).value
예제 #34
0
def ptr_add(ptr, offset):
    address = ctypes.addressof(ptr.contents) + offset
    return ctypes.pointer(type(ptr.contents).from_address(address))
예제 #35
0
 def read(self, offset: int, size: int) -> int:
     buf = ctypes.create_string_buffer(size)
     ctypes.memmove(buf, ctypes.addressof(self.dma) + offset, size)
     retval = int.from_bytes(buf.raw, byteorder='little')
     return retval
예제 #36
0
 def __repr__(self):
     "Short-hand representation because WKT may be very large."
     return '<%s object at %s>' % (self.geom_type, hex(addressof(self.ptr)))
예제 #37
0
import blowfish
import mmap
import ctypes

key = bytes(sys.argv[1], 'utf-8')
enc_shellcode = bytes.fromhex(sys.argv[2].replace('\\x', ''))

iv = b'\x00\x00\x00\x00\x00\x00\x00\x00'  #urandom(8)
cipher = blowfish.Cipher(key)
blocks = cipher.decrypt_cfb(enc_shellcode, iv)

shellcode = []
for block in blocks:
    for byte in block:
        shellcode.append(byte)

shellcode_bytes = bytes(shellcode)

# execute shellcode
exec_mem = mmap.mmap(-1,
                     len(shellcode_bytes),
                     prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
                     flags=mmap.MAP_ANONYMOUS | mmap.MAP_PRIVATE)
exec_mem.write(shellcode_bytes)

ctypes_buffer = ctypes.c_int.from_buffer(exec_mem)
func = ctypes.CFUNCTYPE(ctypes.c_int64)(ctypes.addressof(ctypes_buffer))
func._avoid_gc_for_mmap = exec_mem

func()
예제 #38
0
 def _convert_to_address(self, BClass):
     if BClass in (CTypesPtr, None) or BClass._automatic_casts:
         return ctypes.addressof(self._blob)
     else:
         return CTypesData._convert_to_address(self, BClass)
예제 #39
0
 def _get_own_repr(self):
     return self._addr_repr(ctypes.addressof(self._blob))
예제 #40
0
 def getter(self, fname=fname, BFieldPtr=BField._CTPtr,
            offset=CTypesStructOrUnion._offsetof(fname),
            PTR=ctypes.POINTER(BField._ctype)):
     addr = ctypes.addressof(self._blob)
     p = ctypes.cast(addr + offset, PTR)
     return BFieldPtr._from_ctypes(p)
예제 #41
0
# NB: we have to specify func names and argtypes (that's deficiency of
#     numba and ctypes interaction)
code = """\
void sq(double* a)
{
  *a = (*a)*(*a);
}
"""
func_name = "sq"
func_argtypes = (ctypes.c_void_p,)
sq = cjit(code, func_name, func_argtypes)


# Example 1: execute function from ctypes
z = ctypes.c_double(42)
sq(ctypes.addressof(z))
print(z.value)


# Examples 2: execute function from Numba
sizeof_double = ctypes.sizeof(ctypes.c_double)

@numba.jit(nopython=True)
def vecsq(a):
    for i in range(a.size):
        sq(a.ctypes.data + i*sizeof_double)

v = numpy.arange(1024, dtype=numpy.double)
vecsq(v)
print(v)
예제 #42
0
 def _convert_to_address(self, BClass):
     if getattr(BClass, '_BItem', None) is self.__class__:
         return ctypes.addressof(self._blob)
     else:
         return CTypesData._convert_to_address(self, BClass)
예제 #43
0
 def __eq__(self, other):
     if not isinstance(other, self.__class__):
         return NotImplemented
     return ctypes.addressof(self.handle.contents) == ctypes.addressof(
         other.handle.contents)
예제 #44
0
 def write_variable(self, BType, name, value):
     new_ctypes_obj = BType._to_ctypes(value)
     ctypes_obj = BType._ctype.in_dll(self.cdll, name)
     ctypes.memmove(ctypes.addressof(ctypes_obj),
                    ctypes.addressof(new_ctypes_obj),
                    ctypes.sizeof(BType._ctype))
예제 #45
0
    def __mainloop(self):

        if not self.__vp_valid:
            self.__vp_size = [glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)]
            self.__vp_valid = True
            glViewport(0, 0, self.__vp_size[0], self.__vp_size[1])

        glClearColor(0.2, 0.3, 0.3, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
          
        index_case = 12
        if index_case == 0:  
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, self.indexArray)

        elif index_case == 1:
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        elif index_case == 2:
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, ctypes.c_void_p(3 * 4))
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        elif index_case == 3:
            indexArray1 = (ctypes.c_uint32 * 3)(0, 1, 2)
            indexArray2 = (ctypes.c_uint32 * 3)(0, 2, 3)
            #indexArray1 = numpy.array([0, 1, 2], dtype=numpy.uint32)
            #indexArray2 = numpy.array([0, 2, 3], dtype=numpy.uint32)
            #offset   = numpy.array([3, 3], dtype=numpy.uint32)
            counts   = [3, 3]
            indexPtr = (ctypes.c_void_p * 2)(ctypes.addressof(indexArray1), ctypes.addressof(indexArray2))
            #indexPtr = numpy.array([indexArray1.ctypes.data, indexArray2.ctypes.data], dtype=numpy.intp)
            glMultiDrawElements(GL_TRIANGLES, counts, GL_UNSIGNED_INT, indexPtr, 2)

        elif index_case == 4:
            indexArray1 = (GLuint * 3)(0, 1, 2)
            indexArray2 = (GLuint * 3)(0, 2, 3)
            counts   = [3, 3]
            indexPtr = (GLvoidp * 2)(ctypes.addressof(indexArray1), ctypes.addressof(indexArray2))
            glMultiDrawElements(GL_TRIANGLES, counts, GL_UNSIGNED_INT, indexPtr, 2)

        elif index_case == 5:
            counts   = [3, 3]
            indexPtr = (ctypes.c_void_p * 2)(0, 3 * 4)
            #indexPtr = numpy.array([0, 3 * 4], dtype=numpy.intp)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glMultiDrawElements(GL_TRIANGLES, counts, GL_UNSIGNED_INT, indexPtr, 2)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        elif index_case == 6:  
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElementsBaseVertex(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None, 0)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        if index_case == 7:  
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None, 1)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        if index_case == 8:  
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElementsInstancedBaseVertex(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None, 1, 0)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        if index_case == 9:  
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElementsInstancedBaseInstance(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None, 1, 0)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        if index_case == 10:  
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None, 1, 0, 0)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        elif index_case == 11:
            # GLAPI/glDrawElementsIndirect
            # https://www.khronos.org/opengl/wiki/GLAPI/glDrawElementsIndirect
            glBindBuffer(GL_DRAW_INDIRECT_BUFFER, self.__darw_indirect_bo[0])
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, None)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
            glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0)
        
        elif index_case == 12:
            # GLAPI/glMultiDrawElementsIndirect
            # https://www.khronos.org/opengl/wiki/GLAPI/glMultiDrawElementsIndirect
            glBindBuffer(GL_DRAW_INDIRECT_BUFFER, self.__darw_indirect_bo[1])
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__vbo[1])
            glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, None, 2, 4*5)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
            glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0)

        elif index_case == 13:
            first = [0, 1]
            counts = [3, 3]
            glMultiDrawArrays(GL_TRIANGLES, first, counts, 2)

        glutSwapBuffers()
        glutPostRedisplay()
예제 #46
0
 def __init__(self) -> None:
     self.lib = c.cdll.LoadLibrary(fname)
     self.flash_size = c.cast(self.lib.FLASH_SIZE, c.POINTER(c.c_uint32))[0]
     self.flash_buffer = c.create_string_buffer(self.flash_size)
     c.cast(self.lib.FLASH_BUFFER,
            c.POINTER(c.c_void_p))[0] = c.addressof(self.flash_buffer)
예제 #47
0
 def getenumerated(self, strcommand):
     """Run command and set Enumerated return value.
     """
     result = ct.c_int()
     command = ct.c_wchar_p(strcommand)
     self.lib.AT_GetEnumerated(self.AT_H, command, ct.addressof(result))
예제 #48
0
 def inject(name, val):
     symbol_name = "_numba_hashsecret_{}".format(name)
     val = ctypes.c_uint64(val)
     addr = ctypes.addressof(val)
     ll.add_symbol(symbol_name, addr)
     info[name] = _hashsecret_entry(symbol=symbol_name, value=val)
예제 #49
0
    def testUpdate(self):

        network = IECoreScene.ShaderNetwork(shaders={
            "noiseHandle":
            IECoreScene.Shader("noise"),
            "flatHandle":
            IECoreScene.Shader("flat"),
        },
                                            connections=[
                                                (("noiseHandle", ""),
                                                 ("flatHandle", "color")),
                                            ],
                                            output="flatHandle")

        with IECoreArnold.UniverseBlock(writable=True) as universe:

            # Convert

            nodes = IECoreArnoldPreview.ShaderNetworkAlgo.convert(
                network, universe, "test")

            def assertNoiseAndFlatNodes():

                self.assertEqual(len(nodes), 2)
                self.assertEqual(
                    arnold.AiNodeEntryGetName(
                        arnold.AiNodeGetNodeEntry(nodes[0])), "noise")
                self.assertEqual(
                    arnold.AiNodeEntryGetName(
                        arnold.AiNodeGetNodeEntry(nodes[1])), "flat")

                self.assertEqual(arnold.AiNodeGetName(nodes[0]),
                                 "test:noiseHandle")
                self.assertEqual(arnold.AiNodeGetName(nodes[1]), "test")

                self.assertEqual(
                    ctypes.addressof(
                        arnold.AiNodeGetLink(nodes[1], "color").contents),
                    ctypes.addressof(nodes[0].contents))

            assertNoiseAndFlatNodes()

            # Convert again with no changes at all. We want to see the same nodes reused.

            originalNodes = nodes[:]
            self.assertTrue(
                IECoreArnoldPreview.ShaderNetworkAlgo.update(nodes, network))
            assertNoiseAndFlatNodes()

            self.assertEqual(ctypes.addressof(nodes[0].contents),
                             ctypes.addressof(originalNodes[0].contents))
            self.assertEqual(ctypes.addressof(nodes[1].contents),
                             ctypes.addressof(originalNodes[1].contents))

            # Convert again with a tweak to a noise parameter. We want to see the same nodes
            # reused, with the new parameter value taking hold.

            noise = network.getShader("noiseHandle")
            noise.parameters["octaves"] = IECore.IntData(3)
            network.setShader("noiseHandle", noise)

            originalNodes = nodes[:]
            self.assertTrue(
                IECoreArnoldPreview.ShaderNetworkAlgo.update(nodes, network))
            assertNoiseAndFlatNodes()

            self.assertEqual(ctypes.addressof(nodes[0].contents),
                             ctypes.addressof(originalNodes[0].contents))
            self.assertEqual(ctypes.addressof(nodes[1].contents),
                             ctypes.addressof(originalNodes[1].contents))
            self.assertEqual(arnold.AiNodeGetInt(nodes[0], "octaves"), 3)

            # Remove the noise shader, and replace it with an image. Make sure the new network is as we expect, and
            # the old noise node has been destroyed.

            network.removeShader("noiseHandle")
            network.setShader("imageHandle", IECoreScene.Shader("image"))
            network.addConnection(
                (("imageHandle", ""), ("flatHandle", "color")))

            originalNodes = nodes[:]
            self.assertTrue(
                IECoreArnoldPreview.ShaderNetworkAlgo.update(nodes, network))

            self.assertEqual(ctypes.addressof(nodes[1].contents),
                             ctypes.addressof(originalNodes[1].contents))

            self.assertEqual(
                arnold.AiNodeEntryGetName(arnold.AiNodeGetNodeEntry(nodes[0])),
                "image")
            self.assertEqual(
                arnold.AiNodeEntryGetName(arnold.AiNodeGetNodeEntry(nodes[1])),
                "flat")

            self.assertEqual(arnold.AiNodeGetName(nodes[0]),
                             "test:imageHandle")
            self.assertEqual(arnold.AiNodeGetName(nodes[1]), "test")

            self.assertEqual(
                ctypes.addressof(
                    arnold.AiNodeGetLink(nodes[1], "color").contents),
                ctypes.addressof(nodes[0].contents))

            self.assertIsNone(
                arnold.AiNodeLookUpByName(universe, "test:noiseHandle"))

            # Replace the output shader with something else.

            network.removeShader("flatHandle")
            network.setShader("lambertHandle", IECoreScene.Shader("lambert"))
            network.addConnection(
                (("imageHandle", ""), ("lambertHandle", "Kd_color")))
            network.setOutput(("lambertHandle", ""))

            originalNodes = nodes[:]
            self.assertFalse(
                IECoreArnoldPreview.ShaderNetworkAlgo.update(nodes, network))

            self.assertEqual(ctypes.addressof(nodes[0].contents),
                             ctypes.addressof(originalNodes[0].contents))

            self.assertEqual(
                arnold.AiNodeEntryGetName(arnold.AiNodeGetNodeEntry(nodes[0])),
                "image")
            self.assertEqual(
                arnold.AiNodeEntryGetName(arnold.AiNodeGetNodeEntry(nodes[1])),
                "lambert")

            self.assertEqual(arnold.AiNodeGetName(nodes[0]),
                             "test:imageHandle")
            self.assertEqual(arnold.AiNodeGetName(nodes[1]), "test")

            self.assertEqual(
                ctypes.addressof(
                    arnold.AiNodeGetLink(nodes[1], "Kd_color").contents),
                ctypes.addressof(nodes[0].contents))
예제 #50
0
    def initialize(self, obj):

        if isinstance(obj, PETSc.PC):
            A, P = obj.getOperators()
        elif isinstance(obj, PETSc.SNES):
            A, P = obj.ksp.pc.getOperators()
        else:
            raise ValueError("Not a PC or SNES?")

        ctx = get_appctx(obj.getDM())
        if ctx is None:
            raise ValueError("No context found on form")
        if not isinstance(ctx, _SNESContext):
            raise ValueError("Don't know how to get form from %r", ctx)

        if P.getType() == "python":
            ictx = P.getPythonContext()
            if ictx is None:
                raise ValueError("No context found on matrix")
            if not isinstance(ictx, ImplicitMatrixContext):
                raise ValueError("Don't know how to get form from %r", ictx)
            J = ictx.a
            bcs = ictx.row_bcs
            if bcs != ictx.col_bcs:
                raise NotImplementedError("Row and column bcs must match")
        else:
            J = ctx.Jp or ctx.J
            bcs = ctx._problem.bcs

        mesh = J.ufl_domain()
        self.plex = mesh.topology_dm
        # We need to attach the mesh to the plex, so that
        # PlaneSmoothers (and any other user-customised patch
        # constructors) can use firedrake's opinion of what
        # the coordinates are, rather than plex's.
        self.plex.setAttr("__firedrake_mesh__", weakref.proxy(mesh))
        self.ctx = ctx

        if mesh.cell_set._extruded:
            raise NotImplementedError("Not implemented on extruded meshes")

        if "overlap_type" not in mesh._distribution_parameters:
            if mesh.comm.size > 1:
                # Want to do
                # warnings.warn("You almost surely want to set an overlap_type in your mesh's distribution_parameters.")
                # but doesn't warn!
                PETSc.Sys.Print(
                    "Warning: you almost surely want to set an overlap_type in your mesh's distribution_parameters."
                )

        patch = obj.__class__().create(comm=obj.comm)
        patch.setOptionsPrefix(obj.getOptionsPrefix() + "patch_")
        self.configure_patch(patch, obj)
        patch.setType("patch")

        if isinstance(obj, PETSc.SNES):
            Jstate = ctx._problem.u
            is_snes = True
        else:
            Jstate = None
            is_snes = False

        V, _ = map(operator.methodcaller("function_space"), J.arguments())

        if len(bcs) > 0:
            ghost_bc_nodes = numpy.unique(
                numpy.concatenate([bcdofs(bc, ghost=True) for bc in bcs]))
            global_bc_nodes = numpy.unique(
                numpy.concatenate([bcdofs(bc, ghost=False) for bc in bcs]))
        else:
            ghost_bc_nodes = numpy.empty(0, dtype=PETSc.IntType)
            global_bc_nodes = numpy.empty(0, dtype=PETSc.IntType)

        Jcell_kernels, Jint_facet_kernels = matrix_funptr(J, Jstate)
        Jcell_kernel, = Jcell_kernels
        Jop_data_args, Jop_map_args = make_c_arguments(
            J, Jcell_kernel, Jstate, operator.methodcaller("cell_node_map"))
        code, Struct = make_jacobian_wrapper(Jop_data_args, Jop_map_args)
        Jop_function = load_c_function(code, "ComputeJacobian", obj.comm)
        Jop_struct = make_c_struct(Jop_data_args, Jop_map_args,
                                   Jcell_kernel.funptr, Struct)

        Jhas_int_facet_kernel = False
        if len(Jint_facet_kernels) > 0:
            Jint_facet_kernel, = Jint_facet_kernels
            Jhas_int_facet_kernel = True
            facet_Jop_data_args, facet_Jop_map_args = make_c_arguments(
                J,
                Jint_facet_kernel,
                Jstate,
                operator.methodcaller("interior_facet_node_map"),
                require_facet_number=True)
            code, Struct = make_jacobian_wrapper(facet_Jop_data_args,
                                                 facet_Jop_map_args)
            facet_Jop_function = load_c_function(code, "ComputeJacobian",
                                                 obj.comm)
            point2facet = J.ufl_domain(
            ).interior_facets.point2facetnumber.ctypes.data
            facet_Jop_struct = make_c_struct(facet_Jop_data_args,
                                             facet_Jop_map_args,
                                             Jint_facet_kernel.funptr,
                                             Struct,
                                             point2facet=point2facet)

        set_residual = hasattr(ctx, "F") and isinstance(obj, PETSc.SNES)
        if set_residual:
            F = ctx.F
            Fstate = ctx._problem.u
            Fcell_kernels, Fint_facet_kernels = residual_funptr(F, Fstate)

            Fcell_kernel, = Fcell_kernels

            Fop_data_args, Fop_map_args = make_c_arguments(
                F,
                Fcell_kernel,
                Fstate,
                operator.methodcaller("cell_node_map"),
                require_state=True)

            code, Struct = make_residual_wrapper(Fop_data_args, Fop_map_args)
            Fop_function = load_c_function(code, "ComputeResidual", obj.comm)
            Fop_struct = make_c_struct(Fop_data_args, Fop_map_args,
                                       Fcell_kernel.funptr, Struct)

            Fhas_int_facet_kernel = False
            if len(Fint_facet_kernels) > 0:
                Fint_facet_kernel, = Fint_facet_kernels
                Fhas_int_facet_kernel = True

                facet_Fop_data_args, facet_Fop_map_args = make_c_arguments(
                    F,
                    Fint_facet_kernel,
                    Fstate,
                    operator.methodcaller("interior_facet_node_map"),
                    require_state=True,
                    require_facet_number=True)
                code, Struct = make_jacobian_wrapper(facet_Fop_data_args,
                                                     facet_Fop_map_args)
                facet_Fop_function = load_c_function(code, "ComputeResidual",
                                                     obj.comm)
                point2facet = F.ufl_domain(
                ).interior_facets.point2facetnumber.ctypes.data
                facet_Fop_struct = make_c_struct(facet_Fop_data_args,
                                                 facet_Fop_map_args,
                                                 Fint_facet_kernel.funptr,
                                                 Struct,
                                                 point2facet=point2facet)

        patch.setDM(self.plex)
        patch.setPatchCellNumbering(mesh._cell_numbering)

        offsets = numpy.append([0], numpy.cumsum([W.dof_count for W in V
                                                  ])).astype(PETSc.IntType)
        patch.setPatchDiscretisationInfo([W.dm for W in V],
                                         numpy.array([W.value_size for W in V],
                                                     dtype=PETSc.IntType),
                                         [W.cell_node_list
                                          for W in V], offsets, ghost_bc_nodes,
                                         global_bc_nodes)
        self.Jop_struct = Jop_struct
        set_patch_jacobian(patch,
                           ctypes.cast(Jop_function, ctypes.c_voidp).value,
                           ctypes.addressof(Jop_struct),
                           is_snes=is_snes)
        if Jhas_int_facet_kernel:
            self.facet_Jop_struct = facet_Jop_struct
            set_patch_jacobian(patch,
                               ctypes.cast(facet_Jop_function,
                                           ctypes.c_voidp).value,
                               ctypes.addressof(facet_Jop_struct),
                               is_snes=is_snes,
                               interior_facets=True)
        if set_residual:
            self.Fop_struct = Fop_struct
            set_patch_residual(patch,
                               ctypes.cast(Fop_function, ctypes.c_voidp).value,
                               ctypes.addressof(Fop_struct),
                               is_snes=is_snes)
            if Fhas_int_facet_kernel:
                set_patch_residual(patch,
                                   ctypes.cast(facet_Fop_function,
                                               ctypes.c_voidp).value,
                                   ctypes.addressof(facet_Fop_struct),
                                   is_snes=is_snes,
                                   interior_facets=True)

        patch.setPatchConstructType(PETSc.PC.PatchConstructType.PYTHON,
                                    operator=self.user_construction_op)
        patch.setAttr("ctx", ctx)
        patch.incrementTabLevel(1, parent=obj)
        patch.setFromOptions()
        patch.setUp()
        self.patch = patch
예제 #51
0
 def __repr__(self):
     """
     Short-hand representation because WKB may be very large.
     """
     return '<Raster object at %s>' % hex(addressof(self._ptr))
예제 #52
0
 def open(self):
     """Open camera self.AT_H.
     """
     camidx = ct.c_int(0)
     self.lib.AT_Open(camidx, ct.addressof(self.AT_H))
     return self.AT_H
예제 #53
0
 def name(self):
     """Returns the name of the model."""
     # The model name is the first null-terminated string in the `names` buffer.
     return util.to_native_string(
         ctypes.string_at(ctypes.addressof(self.names.contents)))
예제 #54
0
 def __hash__(self):
     return hash(("CompiledCode", ctypes.addressof(self.cfunc)))  # XXX hack
예제 #55
0
    def OLDBUF_test_oldbuf_arg(self):
        from pygame.bufferproxy import (get_segcount, get_read_buffer,
                                        get_write_buffer)

        content = as_bytes('\x01\x00\x00\x02') * 12
        memory = ctypes.create_string_buffer(content)
        memaddr = ctypes.addressof(memory)

        def raise_exception(o):
            raise ValueError("An exception")

        bf = BufferProxy({
            'shape': (len(content), ),
            'typestr': '|u1',
            'data': (memaddr, False),
            'strides': (1, )
        })
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, 0)
        self.assertEqual(seglen, 0)
        seglen, segaddr = get_write_buffer(bf, 0)
        self.assertEqual(segaddr, 0)
        self.assertEqual(seglen, 0)
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 1)
        self.assertEqual(buflen, len(content))
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))
        seglen, segaddr = get_write_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))

        bf = BufferProxy({
            'shape': (len(content), ),
            'typestr': '|u1',
            'data': (memaddr, True),
            'strides': (1, )
        })
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 1)
        self.assertEqual(buflen, len(content))
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))
        self.assertRaises(ValueError, get_write_buffer, bf, 0)

        bf = BufferProxy({
            'shape': (len(content), ),
            'typestr': '|u1',
            'data': (memaddr, True),
            'strides': (1, ),
            'before': raise_exception
        })
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 0)
        self.assertEqual(buflen, 0)

        bf = BufferProxy({
            'shape': (3, 4),
            'typestr': '|u4',
            'data': (memaddr, True),
            'strides': (12, 4)
        })
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 3 * 4)
        self.assertEqual(buflen, 3 * 4 * 4)
        for i in range(0, 4):
            seglen, segaddr = get_read_buffer(bf, i)
            self.assertEqual(segaddr, memaddr + i * 4)
            self.assertEqual(seglen, 4)
예제 #56
0
    def expos(self):
        """
        fill the buffers and return a science frame
        """

        self.start_time = ("""%s""" % datetime.datetime.utcnow()).replace(
            ' ', 'T')

        #        unstacked = np.empty((300,240,320),dtype='uint16')

        #        medianList=[]
        #        data=np.zeros((240,320))
        flat_data = np.zeros((240, 320), dtype='float32')
        for i in range(int(self.expos_time)
                       ):  #allows integer values of longer than one second
            # #Use this to see individual frames

            #        dataList=[]
            # start filling the buffers
            rval = self.imaq.imgSessionStartAcquisition(self.sid)

            sleep(1.1)

            rval = self.imaq.imgSessionStopAcquisition(self.sid)

            for j in xrange(60):  #gives one second of data
                np_buffer = np.core.multiarray.int_asbuffer(
                    C.addressof(self.bufList[j].contents), self.bufSize)
                flat_data += np.reshape(
                    np.frombuffer(np_buffer, dtype='uint16'), (240, 320))


#                unstacked[(i*60)+j]=buf
#                print np.median(unstacked)

#got rid of this median correction stuff.  could be reimplemented later
#            med=np.median(flat_data)
#            med_reduced_data=flat_data/med
#            medianList.append(med)
#            data+=med_reduced_data

#            x = np.frombuffer(np_buffer,dtype=np.uint16)

#            flat_data += x
#            dataList.append(np.array(x))

            self.stop_time = ("""%s""" % datetime.datetime.utcnow()).replace(
                ' ', 'T')

            # #These next two lines create the array of pointers for the buffer
            imgbuffer = C.POINTER(C.c_uint16) * self.bufNum

            # #creates a list of empty buffers
            self.bufList = imgbuffer()

            self.rval = self.imaq.imgRingSetup(self.sid, self.bufNum,
                                               self.bufList, 0, 0)

        self.img = flat_data
        #        self.img = data*np.median(medianList)
        #        self.img_raw=unstacked
        #        self.dList=dataList

        ser = serial.Serial(port=0, baudrate=57600)
        ser.write("camera:temp?\r")
        self.TEMP = int(ser.read(15)[13:])
        ser.close()
예제 #57
0
def ctypes_ref_set_uint(ref, num):
    "Assigns an integer to a ctypes reference to an unsigned integer."

    cnum = ctypes.c_uint(num)
    ctypes.memmove(ref, ctypes.addressof(cnum), ctypes.sizeof(cnum))
예제 #58
0
class BufferProxyLegacyTest(unittest.TestCase):
    content = as_bytes('\x01\x00\x00\x02') * 12
    buffer = ctypes.create_string_buffer(content)
    data = (ctypes.addressof(buffer), True)

    def test_length(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.length:

        # The size of the buffer data in bytes.
        bf = BufferProxy({
            'shape': (3, 4),
            'typestr': '|u4',
            'data': self.data,
            'strides': (12, 4)
        })
        self.assertEqual(bf.length, len(self.content))
        bf = BufferProxy({
            'shape': (3, 3),
            'typestr': '|u4',
            'data': self.data,
            'strides': (12, 4)
        })
        self.assertEqual(bf.length, 3 * 3 * 4)

    def test_raw(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.raw:

        # The raw buffer data as string. The string may contain NUL bytes.

        bf = BufferProxy({
            'shape': (len(self.content), ),
            'typestr': '|u1',
            'data': self.data
        })
        self.assertEqual(bf.raw, self.content)
        bf = BufferProxy({
            'shape': (3, 4),
            'typestr': '|u4',
            'data': self.data,
            'strides': (4, 12)
        })
        self.assertEqual(bf.raw, self.content)
        bf = BufferProxy({
            'shape': (3, 4),
            'typestr': '|u1',
            'data': self.data,
            'strides': (16, 4)
        })
        self.assertRaises(ValueError, getattr, bf, 'raw')

    def test_write(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.write:

        # B.write (bufferproxy, buffer, offset) -> None
        #
        # Writes raw data to the bufferproxy.
        #
        # Writes the raw data from buffer to the BufferProxy object, starting
        # at the specified offset within the BufferProxy.
        # If the length of the passed buffer exceeds the length of the
        # BufferProxy (reduced by the offset), an IndexError will be raised.
        from ctypes import c_byte, sizeof, addressof, string_at, memset

        nullbyte = '\x00'.encode('latin_1')
        Buf = c_byte * 10
        data_buf = Buf(*range(1, 3 * sizeof(Buf) + 1, 3))
        data = string_at(data_buf, sizeof(data_buf))
        buf = Buf()
        bp = BufferProxy({
            'typestr': '|u1',
            'shape': (sizeof(buf), ),
            'data': (addressof(buf), False)
        })
        try:
            self.assertEqual(bp.raw, nullbyte * sizeof(Buf))
            bp.write(data)
            self.assertEqual(bp.raw, data)
            memset(buf, 0, sizeof(buf))
            bp.write(data[:3], 2)
            raw = bp.raw
            self.assertEqual(raw[:2], nullbyte * 2)
            self.assertEqual(raw[2:5], data[:3])
            self.assertEqual(raw[5:], nullbyte * (sizeof(Buf) - 5))
            bp.write(data[:3], bp.length - 3)
            raw = bp.raw
            self.assertEqual(raw[-3:], data[:3])
            self.assertRaises(IndexError, bp.write, data, 1)
            self.assertRaises(IndexError, bp.write, data[:5], -1)
            self.assertRaises(IndexError, bp.write, data[:5], bp.length)
            self.assertRaises(TypeError, bp.write, 12)
            bp = BufferProxy({
                'typestr': '|u1',
                'shape': (sizeof(buf), ),
                'data': (addressof(buf), True)
            })
            self.assertRaises(pygame.BufferError, bp.write,
                              '123'.encode('latin_1'))
        finally:
            # Make sure bp is garbage collected before buf
            bp = None
            gc.collect()
예제 #59
0
파일: render.py 프로젝트: stshow/kitty
def render_box_drawing(codepoint, cell_width, cell_height, dpi):
    CharTexture = ctypes.c_ubyte * (cell_width * cell_height)
    buf = render_box_char(chr(codepoint), CharTexture(), cell_width,
                          cell_height, dpi)
    return ctypes.addressof(buf), buf
예제 #60
0
# Fortranでアドレスからvec_t[Fortran]に変換して利用する。

import ctypes


# Pythonで作成したC互換なデータ型
class Vec(ctypes.Structure):
    _fields_ = [
        ("x", ctypes.c_double),
        ("y", ctypes.c_double),
        ("z", ctypes.c_double),
    ]

    def __repr__(self):
        className = self.__class__.__name__
        valueList = ", ".join("{}={}".format(attr, getattr(self, attr))
                              for attr, _ in self._fields_)
        return "{className}({valueList})".format(**vars())


# 下記データ型と対応する。
# C | struct _vec_t {
# C |     double x, y, z;
# C | };

vec = Vec(10, 20, 30)

print(vec)
struct_vec_rotate(ctypes.addressof(vec))
print(vec)