Python ctypes.memmove() Examples

The following are 30 code examples of ctypes.memmove(). 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: __init__.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
def consume(self, bytes, audio_format):
        '''Remove some data from beginning of packet.'''
        if bytes == self.length:
            self.data = None
            self.length = 0
            self.timestamp += self.duration
            self.duration = 0.
            return
        elif bytes == 0:
            return

        if not isinstance(self.data, str):
            # XXX Create a string buffer for the whole packet then
            #     chop it up.  Could do some pointer arith here and
            #     save a bit of data pushing, but my guess is this is
            #     faster than fudging aruond with ctypes (and easier).
            data = ctypes.create_string_buffer(self.length)
            ctypes.memmove(data, self.data, self.length)
            self.data = data
        self.data = self.data[bytes:]
        self.length -= bytes
        self.duration -= bytes / float(audio_format.bytes_per_second)
        self.timestamp += bytes / float(audio_format.bytes_per_second) 
Example #2
Source File: test_jlink.py    From pylink with Apache License 2.0 6 votes vote down vote up
def test_jlink_features_has_features(self):
        """Tests the J-Link ``features`` property returns a feature list.

        Args:
          self (TestJLink): the ``TestJLink`` instance

        Returns:
          ``None``
        """
        feature_string = 'RDI, JFlash, FlashDL'

        def func(b):
            ctypes.memmove(b, feature_string.encode(), len(feature_string))

        self.dll.JLINKARM_GetFeatureString = func

        result = self.jlink.features

        self.assertTrue(isinstance(result, list))
        self.assertEqual(3, len(result))
        self.assertEqual('RDI', result[0])
        self.assertEqual('JFlash', result[1])
        self.assertEqual('FlashDL', result[2]) 
Example #3
Source File: test_jlink.py    From pylink with Apache License 2.0 6 votes vote down vote up
def test_jlink_compatible_firmware_version(self):
        """Tests that getting a compatible firmware version from the DLL.

        Args:
          self (TestJLink): the ``TestJLink`` instance

        Returns:
          ``None``
        """
        firmware = 'J-Trace Cortex-M Rev.3 compiled Mar 30 2015 13:52:25'

        def set_firmware_string(buf, buf_size):
            ctypes.memmove(buf, firmware.encode(), len(firmware))

        self.dll.JLINKARM_GetFirmwareString = set_firmware_string

        self.dll.JLINKARM_GetEmbeddedFWString.return_value = -1
        with self.assertRaises(JLinkException):
            self.jlink.compatible_firmware_version

        self.dll.JLINKARM_GetEmbeddedFWString.return_value = 0
        self.dll.JLINKARM_GetEmbeddedFWString.assert_called()
        self.assertEqual('', self.jlink.compatible_firmware_version) 
Example #4
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
def consume(self, bytes, audio_format):
        '''Remove some data from beginning of packet.'''
        if bytes == self.length:
            self.data = None
            self.length = 0
            self.timestamp += self.duration
            self.duration = 0.
            return
        elif bytes == 0:
            return

        if not isinstance(self.data, str):
            # XXX Create a string buffer for the whole packet then
            #     chop it up.  Could do some pointer arith here and
            #     save a bit of data pushing, but my guess is this is
            #     faster than fudging aruond with ctypes (and easier).
            data = ctypes.create_string_buffer(self.length)
            ctypes.memmove(data, self.data, self.length)
            self.data = data
        self.data = self.data[bytes:]
        self.length -= bytes
        self.duration -= bytes / float(audio_format.bytes_per_second)
        self.timestamp += bytes / float(audio_format.bytes_per_second) 
Example #5
Source File: _base.py    From training_results_v0.6 with Apache License 2.0 6 votes vote down vote up
def ctypes2buffer(cptr, length):
    """Convert ctypes pointer to buffer type.

    Parameters
    ----------
    cptr : ctypes.POINTER(ctypes.c_char)
        pointer to the raw memory region
    length : int
        the length of the buffer

    Returns
    -------
    buffer : bytearray
        The raw byte memory buffer
    """
    if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
        raise TypeError('expected char pointer')
    res = bytearray(length)
    rptr = (ctypes.c_char * length).from_buffer(res)
    if not ctypes.memmove(rptr, cptr, length):
        raise RuntimeError('memmove failed')
    return res 
Example #6
Source File: evntprov.py    From pywintrace with Apache License 2.0 6 votes vote down vote up
def __init__(self, match_any, match_all, level, filter_in, names):
        struct_size = ((sum([len(name) for name in names]) * ct.sizeof(wt.CHAR)) + (ct.sizeof(wt.CHAR) * len(names))) +\
                      ct.sizeof(EVENT_FILTER_EVENT_NAME)
        self._buf = (ct.c_char * struct_size)()
        self._props = ct.cast(ct.pointer(self._buf), ct.POINTER(EVENT_FILTER_EVENT_NAME))
        self._props.contents.MatchAnyKeyword = match_any
        self._props.contents.MatchAllKeyword = match_all
        self._props.contents.Level = level
        self._props.contents.FilterIn = filter_in
        self._props.contents.NameCount = len(names)

        str_off = 0
        for i in range(len(names)):
            ct.memmove(ct.cast(ct.addressof(self._buf) + ct.sizeof(EVENT_FILTER_EVENT_NAME) + str_off,
                               ct.c_void_p),
                       names[i],
                       len(names[i]))
            str_off += len(names[i]) + ct.sizeof(wt.CHAR) 
Example #7
Source File: etw.py    From pywintrace with Apache License 2.0 6 votes vote down vote up
def __init__(self, event_property, event_filters):
        """
        Initializes an ENABLE_TRACE_PARAMETERS structure.

        :param event_property: Property to enable.
                         See https://msdn.microsoft.com/en-us/library/windows/desktop/dd392306(v=vs.85).aspx
        :param event_filters: List of EVENT_FILTER_DESCRIPTOR structures
        """

        self._props = ct.pointer(et.ENABLE_TRACE_PARAMETERS())

        filter_buf_size = ct.sizeof(ep.EVENT_FILTER_DESCRIPTOR) * len(event_filters)
        # noinspection PyCallingNonCallable
        filter_buf = (ct.c_char * filter_buf_size)()
        # copy contents to buffer
        for i in range(len(event_filters)):
            ct.memmove(ct.cast(ct.addressof(filter_buf) + (ct.sizeof(ep.EVENT_FILTER_DESCRIPTOR) * i), ct.c_void_p),
                       ct.byref(event_filters[i]),
                       ct.sizeof(ep.EVENT_FILTER_DESCRIPTOR))

        self._props.contents.Version = et.ENABLE_TRACE_PARAMETERS_VERSION_2
        self._props.contents.EnableProperty = event_property
        self._props.contents.ControlFlags = 0
        self._props.contents.EnableFilterDesc = ct.cast(ct.pointer(filter_buf), ct.POINTER(ep.EVENT_FILTER_DESCRIPTOR))
        self._props.contents.FilterDescCount = len(event_filters) 
Example #8
Source File: base.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def ctypes2buffer(cptr, length):
    """Convert ctypes pointer to buffer type.

    Parameters
    ----------
    cptr : ctypes.POINTER(ctypes.c_char)
        Pointer to the raw memory region.
    length : int
        The length of the buffer.

    Returns
    -------
    buffer : bytearray
        The raw byte memory buffer.
    """
    if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
        raise TypeError('expected char pointer')
    res = bytearray(length)
    rptr = (ctypes.c_char * length).from_buffer(res)
    if not ctypes.memmove(rptr, cptr, length):
        raise RuntimeError('memmove failed')
    return res 
Example #9
Source File: vertexbuffer.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def resize(self, size):
        array = (ctypes.c_byte * size)()
        ctypes.memmove(array, self.array, min(size, self.size))
        self.size = size
        self.array = array
        self.ptr = ctypes.cast(self.array, ctypes.c_void_p).value 
Example #10
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def write(self, audio_data, length=None):
        # Pass audio_data=None, length>0 to write silence
        if length is None:
            write_size = self.get_write_size()
            length = min(audio_data.length, write_size)
        if length == 0:
            return 0

        if self._data_size < self._buffer_size:
            self._data_size = min(self._data_size + length, self._buffer_size)

        p1 = ctypes.c_void_p()
        l1 = lib.DWORD()
        p2 = ctypes.c_void_p()
        l2 = lib.DWORD()
        self._buffer.Lock(self._write_cursor, length,
            ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0)
        assert length == l1.value + l2.value

        if audio_data:
            if self._write_cursor >= self._play_cursor:
                wc = self._write_cursor
            else:
                wc = self._write_cursor + self._buffer_size
            self._timestamps.append((wc, audio_data.timestamp))

            ctypes.memmove(p1, audio_data.data, l1.value)
            audio_data.consume(l1.value, self.audio_format)
            if l2.value:
                ctypes.memmove(p2, audio_data.data, l2.value)
                audio_data.consume(l2.value, self.audio_format)
        else:
            ctypes.memset(p1, 0, l1.value)
            if l2.value:
                ctypes.memset(p2, 0, l2.value)
                pass
        self._buffer.Unlock(p1, l1, p2, l2)

        self._write_cursor += length
        self._write_cursor %= self._buffer_size 
Example #11
Source File: vertexbuffer.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def set_data(self, data):
        super(MappableVertexBufferObject, self).set_data(data)
        ctypes.memmove(self.data, data, self.size)
        self._dirty_min = 0
        self._dirty_max = self.size 
Example #12
Source File: vertexbuffer.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def set_data_region(self, data, start, length):
        ctypes.memmove(self.data_ptr + start, data, length)
        self._dirty_min = min(start, self._dirty_min)
        self._dirty_max = max(start + length, self._dirty_max) 
Example #13
Source File: vertexbuffer.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def resize(self, size):
        data = (ctypes.c_byte * size)()
        ctypes.memmove(data, self.data, min(size, self.size))
        self.data = data
        self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value

        self.size = size
        glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
        glBindBuffer(self.target, self.id)
        glBufferData(self.target, self.size, self.data, self.usage)
        glPopClientAttrib()

        self._dirty_min = sys.maxint
        self._dirty_max = 0 
Example #14
Source File: win_inet_pton.py    From PySyncObj with MIT License 5 votes vote down vote up
def inet_ntop(address_family, packed_ip):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))
    ip_string = ctypes.create_string_buffer(128)
    ip_string_size = ctypes.c_int(ctypes.sizeof(ip_string))

    if address_family == socket.AF_INET:
        if len(packed_ip) != ctypes.sizeof(addr.ipv4_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv4_addr, packed_ip, 4)
    elif address_family == socket.AF_INET6:
        if len(packed_ip) != ctypes.sizeof(addr.ipv6_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv6_addr, packed_ip, 16)
    else:
        raise socket.error('unknown address family')

    if WSAAddressToStringA(
            ctypes.byref(addr),
            addr_size,
            None,
            ip_string,
            ctypes.byref(ip_string_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    return ip_string[:ip_string_size.value - 1]

# Adding our two functions to the socket library 
Example #15
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def get_string_data(self):
        '''Return data as a string.'''
        if type(self.data) is str:
            return self.data

        buf = ctypes.create_string_buffer(self.length)
        ctypes.memmove(buf, self.data, self.length)
        return buf.raw 
Example #16
Source File: avbin.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, packet):
        self.timestamp = packet.timestamp
        self.stream_index = packet.stream_index
        self.data = (ctypes.c_uint8 * packet.size)()
        self.size = packet.size
        ctypes.memmove(self.data, packet.data, self.size) 
Example #17
Source File: ae.py    From Splunk-Assessment-of-Mitigation-Implementations with The Unlicense 5 votes vote down vote up
def __init__(self, restype, argtypes, is_64_bit):                            
        # Load in kernel32.dll
        self.kernel32_dll = ctypes.WinDLL("C:\\Windows\\System32\\kernel32.dll")
        opc = self._OPC_64 if is_64_bit == True else self._OPC_32
        self.instructions = "".join((chr(x) for x in opc))
        self.buffer = self.kernel32_dll.VirtualAlloc(None, len(self.instructions),
            (self._MEM_COMMIT | self._MEM_RESERVE), self._PAGE_EXECUTE_READWRITE)
        ctypes.memmove(self.buffer, self.instructions, len(self.instructions))
        proto_func = ctypes.CFUNCTYPE(restype, *argtypes)
        self.cpuid = proto_func(self.buffer) 
Example #18
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def get_string_data(self):
        '''Return data as a string.'''
        if type(self.data) is str:
            return self.data

        buf = ctypes.create_string_buffer(self.length)
        ctypes.memmove(buf, self.data, self.length)
        return buf.raw 
Example #19
Source File: vertexbuffer.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def resize(self, size):
        data = (ctypes.c_byte * size)()
        ctypes.memmove(data, self.data, min(size, self.size))
        self.data = data
        self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value

        self.size = size
        glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
        glBindBuffer(self.target, self.id)
        glBufferData(self.target, self.size, self.data, self.usage)
        glPopClientAttrib()

        self._dirty_min = sys.maxint
        self._dirty_max = 0 
Example #20
Source File: win_inet_pton.py    From script.elementum.burst with Do What The F*ck You Want To Public License 5 votes vote down vote up
def inet_ntop(address_family, packed_ip):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))
    ip_string = ctypes.create_string_buffer(128)
    ip_string_size = ctypes.c_int(ctypes.sizeof(ip_string))

    if address_family == socket.AF_INET:
        if len(packed_ip) != ctypes.sizeof(addr.ipv4_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv4_addr, packed_ip, 4)
    elif address_family == socket.AF_INET6:
        if len(packed_ip) != ctypes.sizeof(addr.ipv6_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv6_addr, packed_ip, 16)
    else:
        raise socket.error('unknown address family')

    if WSAAddressToStringA(
            ctypes.byref(addr),
            addr_size,
            None,
            ip_string,
            ctypes.byref(ip_string_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    return ip_string[:ip_string_size.value - 1]

# Adding our two functions to the socket library 
Example #21
Source File: vertexbuffer.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def set_data_region(self, data, start, length):
        ctypes.memmove(self.ptr + start, data, length) 
Example #22
Source File: vertexbuffer.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def set_data(self, data):
        ctypes.memmove(self.ptr, data, self.size) 
Example #23
Source File: bmp.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def decode_32bit_rgb(bits, palette, width, height, pitch, pitch_sign):
    buffer = (ctypes.c_ubyte * (height * pitch))()
    ctypes.memmove(buffer, bits, len(buffer))
    return ImageData(width, height, 'BGRA', buffer, pitch_sign * pitch) 
Example #24
Source File: receive.py    From RF-Monitor with GNU General Public License v2.0 5 votes vote down vote up
def __capture(self, data, _sdr):
        timestamp = time.time()
        dst = ctypes.byref(self._capture, 0)
        ctypes.memmove(dst, data, len(data))

        iq = self.__stream_to_complex(self._capture)
        l, f = psd(iq, BINS, SAMPLE_RATE,
                   scale_by_freq=False,
                   noverlap=-SAMPLES / 64)
        f /= 1e6
        f += self._freq

        event = Event(Events.SCAN_DATA, timestamp=timestamp, l=l, f=f)
        post_event(self._eventHandler, event) 
Example #25
Source File: bmp.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def decode_24bit(bits, palette, width, height, pitch, pitch_sign):
    buffer = (ctypes.c_ubyte * (height * pitch))()
    ctypes.memmove(buffer, bits, len(buffer))
    return ImageData(width, height, 'BGR', buffer, pitch_sign * pitch) 
Example #26
Source File: avbin.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, packet):
        self.timestamp = packet.timestamp
        self.stream_index = packet.stream_index
        self.data = (ctypes.c_uint8 * packet.size)()
        self.size = packet.size
        ctypes.memmove(self.data, packet.data, self.size) 
Example #27
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def write(self, audio_data, length=None):
        # Pass audio_data=None, length>0 to write silence
        if length is None:
            write_size = self.get_write_size()
            length = min(audio_data.length, write_size)
        if length == 0:
            return 0

        if self._data_size < self._buffer_size:
            self._data_size = min(self._data_size + length, self._buffer_size)

        p1 = ctypes.c_void_p()
        l1 = lib.DWORD()
        p2 = ctypes.c_void_p()
        l2 = lib.DWORD()
        self._buffer.Lock(self._write_cursor, length,
            ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0)
        assert length == l1.value + l2.value

        if audio_data:
            if self._write_cursor >= self._play_cursor:
                wc = self._write_cursor
            else:
                wc = self._write_cursor + self._buffer_size
            self._timestamps.append((wc, audio_data.timestamp))

            ctypes.memmove(p1, audio_data.data, l1.value)
            audio_data.consume(l1.value, self.audio_format)
            if l2.value:
                ctypes.memmove(p2, audio_data.data, l2.value)
                audio_data.consume(l2.value, self.audio_format)
        else:
            ctypes.memset(p1, 0, l1.value)
            if l2.value:
                ctypes.memset(p2, 0, l2.value)
                pass
        self._buffer.Unlock(p1, l1, p2, l2)

        self._write_cursor += length
        self._write_cursor %= self._buffer_size 
Example #28
Source File: __init__.py    From flappy-bird-py with GNU General Public License v2.0 5 votes vote down vote up
def get_string_data(self):
        '''Return data as a string.'''
        if type(self.data) is str:
            return self.data

        buf = ctypes.create_string_buffer(self.length)
        ctypes.memmove(buf, self.data, self.length)
        return buf.raw 
Example #29
Source File: test_ctypes.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cp34892(self):
        src = b''
        buf = ctypes.create_string_buffer(0)
        try:
            ctypes.memmove(ctypes.addressof(buf), src, 0)
        except Exception as ex:
            # there should be no exception of any kind
            self.fail("Unexpected exception: %s" % ex) 
Example #30
Source File: backend_ctypes.py    From learn_python3_spider with MIT License 5 votes vote down vote up
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))