Python ctypes.c_voidp() Examples

The following are 21 code examples of ctypes.c_voidp(). 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_code.py    From android_universal with MIT License 6 votes vote down vote up
def test_free_different_thread(self):
            # Freeing a code object on a different thread then
            # where the co_extra was set should be safe.
            f = self.get_func()
            class ThreadTest(threading.Thread):
                def __init__(self, f, test):
                    super().__init__()
                    self.f = f
                    self.test = test
                def run(self):
                    del self.f
                    self.test.assertEqual(LAST_FREED, 500)

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(500))
            tt = ThreadTest(f, self)
            del f
            tt.start()
            tt.join()
            self.assertEqual(LAST_FREED, 500) 
Example #2
Source File: wrapper.py    From sqrmelon with MIT License 6 votes vote down vote up
def __init__(self, *args):
        assert self.__class__ != VectorBase, 'Instantiation of abstract class.'

        self._data = None
        if args:
            if isinstance(args[0], (long, ctypes.c_voidp, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_wchar_p, ctypes.c_long)):
                self._ptr = args[0]
            elif isinstance(args[0], self.__class__):
                self._ptr = _dllHandle.Vector_Copy(args[0]._ptr)
            else:
                assert len(
                    args) == self.__class__._size and self.__class__._size <= 4, 'Attempting to constructor vector of size {} with either wrong number of arguments {} or beyond maximum size 4.'.format(
                    self.__class__._size, args)
                data = (ctypes.c_float * 4)(*(list(args) + [0] * (4 - self.__class__._size)))
                self._ptr = _dllHandle.Vector_FromFloat4(data)
        else:
            self._ptr = _dllHandle.Vector_Vector() 
Example #3
Source File: _sendfile.py    From Flask-P2P with MIT License 5 votes vote down vote up
def sendfile(fdout, fdin, offset, nbytes):
    if sys.platform == 'darwin':
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                              ctypes.POINTER(ctypes.c_uint64), ctypes.c_voidp,
                              ctypes.c_int]
        _nbytes = ctypes.c_uint64(nbytes)
        result = _sendfile(fdin, fdout, offset, _nbytes, None, 0)

        if result == -1:
            e = ctypes.get_errno()
            if e == errno.EAGAIN and _nbytes.value is not None:
                return _nbytes.value
            raise OSError(e, os.strerror(e))
        return _nbytes.value
    elif sys.platform in ('freebsd', 'dragonfly',):
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                              ctypes.c_uint64, ctypes.c_voidp,
                              ctypes.POINTER(ctypes.c_uint64), ctypes.c_int]
        _sbytes = ctypes.c_uint64()
        result = _sendfile(fdin, fdout, offset, nbytes, None, _sbytes, 0)
        if result == -1:
            e = ctypes.get_errno()
            if e == errno.EAGAIN and _sbytes.value is not None:
                return _sbytes.value
            raise OSError(e, os.strerror(e))
        return _sbytes.value

    else:
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int,
                ctypes.POINTER(ctypes.c_uint64), ctypes.c_size_t]

        _offset = ctypes.c_uint64(offset)
        sent = _sendfile(fdout, fdin, _offset, nbytes)
        if sent == -1:
            e = ctypes.get_errno()
            raise OSError(e, os.strerror(e))
        return sent 
Example #4
Source File: test_code.py    From android_universal with MIT License 5 votes vote down vote up
def test_get_set(self):
            # Test basic get/set round tripping.
            f = self.get_func()

            extra = ctypes.c_voidp()

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
            # reset should free...
            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
            self.assertEqual(LAST_FREED, 200)

            extra = ctypes.c_voidp()
            GetExtra(f.__code__, FREE_INDEX, extra)
            self.assertEqual(extra.value, 300)
            del f 
Example #5
Source File: test_code.py    From android_universal with MIT License 5 votes vote down vote up
def test_free_called(self):
            # Verify that the provided free function gets invoked
            # when the code object is cleaned up.
            f = self.get_func()

            SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100))
            del f
            self.assertEqual(LAST_FREED, 100) 
Example #6
Source File: test_code.py    From android_universal with MIT License 5 votes vote down vote up
def test_bad_index(self):
            f = self.get_func()
            self.assertRaises(SystemError, SetExtra, f.__code__,
                              FREE_INDEX+100, ctypes.c_voidp(100))
            self.assertEqual(GetExtra(f.__code__, FREE_INDEX+100,
                              ctypes.c_voidp(100)), 0) 
Example #7
Source File: test_code.py    From android_universal with MIT License 5 votes vote down vote up
def test_get_non_code(self):
            f = self.get_func()

            self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX,
                              ctypes.c_voidp(100))
            self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX,
                              ctypes.c_voidp(100)) 
Example #8
Source File: codepage.py    From ppci with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_ctypes_type(debug_type):
    if isinstance(debug_type, debuginfo.DebugBaseType):
        return debug_type_name_mapping[debug_type.name]
    elif isinstance(debug_type, debuginfo.DebugPointerType):
        if isinstance(debug_type.pointed_type, debuginfo.DebugStructType):
            # TODO: treat struct pointers as void pointers for now.
            # TODO: fix this?
            return ctypes.c_voidp
        else:
            return ctypes.POINTER(get_ctypes_type(debug_type.pointed_type))
    elif isinstance(debug_type, debuginfo.DebugArrayType):
        element_type = get_ctypes_type(debug_type.element_type)
        return ctypes.ARRAY(element_type, debug_type.size)
    elif debug_type is None:
        return
    elif isinstance(debug_type, type):
        mapping = {int: ctypes.c_int, float: ctypes.c_double}
        return mapping[debug_type]
    elif isinstance(debug_type, ir.BasicTyp):
        mapping = {
            ir.f32: ctypes.c_float,
            ir.f64: ctypes.c_double,
            ir.i32: ctypes.c_int32,
            ir.i64: ctypes.c_int64,  # TODO: which one of 32 and 64 is int?
        }
        return mapping[debug_type]
    else:  # pragma: no cover
        raise NotImplementedError(str(debug_type) + str(type(debug_type))) 
Example #9
Source File: rt_thread.py    From OpenNFB with GNU General Public License v3.0 5 votes vote down vote up
def set_realtime(period, computation, constraint):
	if sys.platform != 'darwin':
		print ('Warning: set_realtime not implemented on this platform')

	global lib
	lib = cdll.LoadLibrary('libSystem.B.dylib')
	lib.pthread_self.restype = c_voidp

	pthread_id = lib.pthread_self()
	thread_id = lib.pthread_mach_thread_np(c_voidp(pthread_id))

	print (pthread_id, thread_id)
	# TODO: conversion from float seconds to mach absolute time values (nanoseconds)


	ttcpolicy = thread_time_constraint_policy(period, computation, constraint, False)
	result = lib.thread_policy_set(c_uint(thread_id), THREAD_TIME_CONSTRAINT_POLICY,
		byref(ttcpolicy), THREAD_TIME_CONSTRAINT_POLICY_COUNT)

	assert result == 0

	tcpolicy = thread_precedence_policy(63)
	#result = lib.thread_policy_set(c_uint(thread_id), THREAD_PRECEDENCE_POLICY,
	#	byref(tcpolicy), THREAD_PRECEDENCE_POLICY_COUNT)

	assert result == 0
	import gc
	gc.disable() 
Example #10
Source File: winamp.py    From collection with MIT License 5 votes vote down vote up
def load_inmod(dllname):
	indll = ctypes.cdll.LoadLibrary(dllname)
	getaddr = indll.winampGetInModule2
	getaddr.restype = c_voidp
	# inmod = (InModule*)(getaddr())
	inmod = cast(getaddr(), POINTER(InModule))[0]
	return inmod

# init inmod/outmod together 
Example #11
Source File: winamp.py    From collection with MIT License 5 votes vote down vote up
def load_outmod(dllname):
	outdll = ctypes.cdll.LoadLibrary(dllname)
	getaddr = outdll.winampGetOutModule
	getaddr.restype = c_voidp
	# outmod = (OutModule*)(getaddr())
	outmod = cast(getaddr(), POINTER(OutModule))[0]
	return outmod

# export InModule from dll 
Example #12
Source File: _sendfile.py    From jbox with MIT License 5 votes vote down vote up
def sendfile(fdout, fdin, offset, nbytes):
    if sys.platform == 'darwin':
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                              ctypes.POINTER(ctypes.c_uint64), ctypes.c_voidp,
                              ctypes.c_int]
        _nbytes = ctypes.c_uint64(nbytes)
        result = _sendfile(fdin, fdout, offset, _nbytes, None, 0)

        if result == -1:
            e = ctypes.get_errno()
            if e == errno.EAGAIN and _nbytes.value is not None:
                return _nbytes.value
            raise OSError(e, os.strerror(e))
        return _nbytes.value
    elif sys.platform in ('freebsd', 'dragonfly',):
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                              ctypes.c_uint64, ctypes.c_voidp,
                              ctypes.POINTER(ctypes.c_uint64), ctypes.c_int]
        _sbytes = ctypes.c_uint64()
        result = _sendfile(fdin, fdout, offset, nbytes, None, _sbytes, 0)
        if result == -1:
            e = ctypes.get_errno()
            if e == errno.EAGAIN and _sbytes.value is not None:
                return _sbytes.value
            raise OSError(e, os.strerror(e))
        return _sbytes.value

    else:
        _sendfile.argtypes = [ctypes.c_int, ctypes.c_int,
                ctypes.POINTER(ctypes.c_uint64), ctypes.c_size_t]

        _offset = ctypes.c_uint64(offset)
        sent = _sendfile(fdout, fdin, _offset, nbytes)
        if sent == -1:
            e = ctypes.get_errno()
            raise OSError(e, os.strerror(e))
        return sent 
Example #13
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _command_line_to_args_list(cmdline):
    """splits a string into a list using Windows command line syntax."""
    args_list = []

    if cmdline and cmdline.strip():
        from ctypes import c_int, c_voidp, c_wchar_p
        from ctypes import byref, POINTER, WinDLL

        clta = WinDLL('shell32').CommandLineToArgvW
        clta.argtypes = [c_wchar_p, POINTER(c_int)]
        clta.restype = POINTER(c_wchar_p)

        lf = WinDLL('kernel32').LocalFree
        lf.argtypes = [c_voidp]

        pNumArgs = c_int()
        r = clta(cmdline, byref(pNumArgs))
        if r:
            for index in range(0, pNumArgs.value):
                if sys.hexversion >= 0x030000F0:
                    argval = r[index]
                else:
                    argval = r[index].encode('ascii', 'replace')
                args_list.append(argval)
            lf(r)
        else:
            sys.stderr.write('Error parsing script arguments:\n')
            sys.stderr.write(cmdline + '\n')

    return args_list 
Example #14
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _command_line_to_args_list(cmdline):
    """splits a string into a list using Windows command line syntax."""
    args_list = []

    if cmdline and cmdline.strip():
        from ctypes import c_int, c_voidp, c_wchar_p
        from ctypes import byref, POINTER, WinDLL

        clta = WinDLL('shell32').CommandLineToArgvW
        clta.argtypes = [c_wchar_p, POINTER(c_int)]
        clta.restype = POINTER(c_wchar_p)

        lf = WinDLL('kernel32').LocalFree
        lf.argtypes = [c_voidp]

        pNumArgs = c_int()
        r = clta(cmdline, byref(pNumArgs))
        if r:
            for index in range(0, pNumArgs.value):
                if sys.hexversion >= 0x030000F0:
                    argval = r[index]
                else:
                    argval = r[index].encode('ascii', 'replace')
                args_list.append(argval)
            lf(r)
        else:
            sys.stderr.write('Error parsing script arguments:\n')
            sys.stderr.write(cmdline + '\n')

    return args_list 
Example #15
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _command_line_to_args_list(cmdline):
    """splits a string into a list using Windows command line syntax."""
    args_list = []

    if cmdline and cmdline.strip():
        from ctypes import c_int, c_voidp, c_wchar_p
        from ctypes import byref, POINTER, WinDLL

        clta = WinDLL('shell32').CommandLineToArgvW
        clta.argtypes = [c_wchar_p, POINTER(c_int)]
        clta.restype = POINTER(c_wchar_p)

        lf = WinDLL('kernel32').LocalFree
        lf.argtypes = [c_voidp]

        pNumArgs = c_int()
        r = clta(cmdline, byref(pNumArgs))
        if r:
            for index in range(0, pNumArgs.value):
                if sys.hexversion >= 0x030000F0:
                    argval = r[index]
                else:
                    argval = r[index].encode('ascii', 'replace')
                args_list.append(argval)
            lf(r)
        else:
            sys.stderr.write('Error parsing script arguments:\n')
            sys.stderr.write(cmdline + '\n')

    return args_list 
Example #16
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _command_line_to_args_list(cmdline):
    """splits a string into a list using Windows command line syntax."""
    args_list = []

    if cmdline and cmdline.strip():
        from ctypes import c_int, c_voidp, c_wchar_p
        from ctypes import byref, POINTER, WinDLL

        clta = WinDLL('shell32').CommandLineToArgvW
        clta.argtypes = [c_wchar_p, POINTER(c_int)]
        clta.restype = POINTER(c_wchar_p)

        lf = WinDLL('kernel32').LocalFree
        lf.argtypes = [c_voidp]

        pNumArgs = c_int()
        r = clta(cmdline, byref(pNumArgs))
        if r:
            for index in range(0, pNumArgs.value):
                if sys.hexversion >= 0x030000F0:
                    argval = r[index]
                else:
                    argval = r[index].encode('ascii', 'replace')
                args_list.append(argval)
            lf(r)
        else:
            sys.stderr.write('Error parsing script arguments:\n')
            sys.stderr.write(cmdline + '\n')

    return args_list 
Example #17
Source File: wrapper.py    From sqrmelon with MIT License 5 votes vote down vote up
def __init__(self, *args):
        self._data = None
        if args:
            if isinstance(args[0], (long, ctypes.c_voidp, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_wchar_p, ctypes.c_long)):
                self._ptr = args[0]
            elif isinstance(args[0], Mat44):
                self._ptr = _dllHandle.Mat44_Copy(args[0]._ptr)
            else:
                data = (ctypes.c_float * 16)(*args)
                self._ptr = _dllHandle.Mat44_FromFloat16(data)
        else:
            self._ptr = _dllHandle.Mat44_Mat44() 
Example #18
Source File: test_ccallback.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _get_ctypes_data():
    value = ctypes.c_double(2.0)
    return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp) 
Example #19
Source File: common.py    From pywintrace with Apache License 2.0 5 votes vote down vote up
def rel_ptr_to_ptr(base, offset):
    """
    Helper function to convert a relative offset to a void pointer.
    """
    return ct.cast((ct.cast(base, ct.c_voidp).value + offset), ct.c_voidp) 
Example #20
Source File: winamp.py    From collection with MIT License 4 votes vote down vote up
def init_modules(inmod, outmod):
	def _SAVSAInit(n1, n2): pass
	def _SAVSADeInit(): pass
	def _SAAddPCMData(n1, n2, n3, n4): pass
	def _SAGetMode(): return 0;
	def _SAAdd(n1, n2, n3): pass
	def _VSAAdd(n1, n2): pass
	def _VSAAddPCMData(n1, n2, n3, n4): pass
	def _VSAGetMode(n1, n2): return 0
	def _VSASetInfo(n1, n2): pass
	def _dspisactive(): return 0
	def _dspyesactive(): return 1
	def _dspdo(n1, n2, n3, n4, n5): return 0
	def _setinfo(n1, n2, n3, n4): pass
	def _eqset(n1, n2, n3): pass

	# setting up default dummy functions
	inmod.SAVSAInit = CFUNCTYPE(None, c_int, c_int)(_SAVSAInit)
	inmod.SAVSADeInit = CFUNCTYPE(None, )(_SAVSADeInit)
	inmod.SAAddPCMData = CFUNCTYPE(None, c_voidp, c_int, c_int, c_int)(_SAAddPCMData)
	inmod.SAGetMode = CFUNCTYPE(c_int,)(_SAGetMode)
	inmod.SAAdd = CFUNCTYPE(None, c_voidp, c_int, c_int)(_SAAdd)
	inmod.VSAAdd = CFUNCTYPE(None, c_voidp, c_int)(_VSAAdd)
	inmod.VSAAddPCMData = CFUNCTYPE(None, c_voidp, c_int, c_int, c_int)(_VSAAddPCMData)
	inmod.VSAGetMode = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))(_VSAGetMode)
	inmod.VSASetInfo = CFUNCTYPE(None, c_int, c_int)(_VSASetInfo)
	inmod.dsp_isactive = CFUNCTYPE(c_int, )(_dspisactive)
	inmod.dsp_dosamples = CFUNCTYPE(c_int, c_voidp, c_int, c_int, c_int, c_int)(_dspdo)
	inmod.setinfo = CFUNCTYPE(None, c_int, c_int, c_int, c_int)(_setinfo)
	inmod.eqset = CFUNCTYPE(None, c_int, c_char_p, c_int)(_eqset)

	# setting up other members
	inmod.outmod = pointer(outmod)
	GetActiveWindow = windll.user32.GetActiveWindow
	inmod.hMainWindow = GetActiveWindow()
	inmod.hDllInstance = 0
	outmod.hMainWindow = GetActiveWindow()
	outmod.hDllInstance = 0

	return  0	


#----------------------------------------------------------------------
# Global Variables
#---------------------------------------------------------------------- 
Example #21
Source File: etw.py    From pywintrace with Apache License 2.0 4 votes vote down vote up
def _getPropertyLength(record, info, event_property):
        """
        Each property encountered when parsing the top level property has an associated length. If the
        length is available, retrieve it here. In some cases, the length is 0. This can signify that
        we are dealing with a variable length field such as a structure, an IPV6 data, or a string.

        :param record: The EventRecord structure for the event we are parsing
        :param info: The TraceEventInfo structure for the event we are parsing
        :param event_property: The EVENT_PROPERTY_INFO structure for the TopLevelProperty of the event we are parsing
        :return: Returns the length of the property as a c_ulong() or None on error
        """
        flags = event_property.Flags

        if flags & tdh.PropertyParamLength:
            data_descriptor = tdh.PROPERTY_DATA_DESCRIPTOR()
            event_property_array = ct.cast(info.contents.EventPropertyInfoArray, ct.POINTER(tdh.EVENT_PROPERTY_INFO))
            j = wt.DWORD(event_property.epi_u3.length)
            property_size = ct.c_ulong()
            length = wt.DWORD()

            # Setup the PROPERTY_DATA_DESCRIPTOR structure
            data_descriptor.PropertyName = (ct.cast(info, ct.c_voidp).value + event_property_array[j.value].NameOffset)
            data_descriptor.ArrayIndex = MAX_UINT

            status = tdh.TdhGetPropertySize(record, 0, None, 1, ct.byref(data_descriptor), ct.byref(property_size))
            if tdh.ERROR_SUCCESS != status:
                raise ct.WinError(status)

            status = tdh.TdhGetProperty(record,
                                        0,
                                        None,
                                        1,
                                        ct.byref(data_descriptor),
                                        property_size,
                                        ct.cast(ct.byref(length), ct.POINTER(ct.c_byte)))
            if tdh.ERROR_SUCCESS != status:
                raise ct.WinError(status)
            return length.value

        in_type = event_property.epi_u1.nonStructType.InType
        out_type = event_property.epi_u1.nonStructType.OutType

        # This is a special case in which the input and output types dictate the size
        if (in_type == tdh.TDH_INTYPE_BINARY) and (out_type == tdh.TDH_OUTTYPE_IPV6):
            return ct.sizeof(ia.IN6_ADDR)

        return event_property.epi_u3.length