Python ctypes.pythonapi() Examples

The following are 15 code examples of ctypes.pythonapi(). 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_android.py    From chaquopy with MIT License 6 votes vote down vote up
def test_ctypes(self):
        from ctypes.util import find_library
        libc = ctypes.CDLL(find_library("c"))
        liblog = ctypes.CDLL(find_library("log"))
        self.assertIsNone(find_library("nonexistent"))

        # Work around double-underscore mangling of __android_log_write.
        def assertHasSymbol(dll, name):
            self.assertIsNotNone(getattr(dll, name))
        def assertNotHasSymbol(dll, name):
            with self.assertRaises(AttributeError):
                getattr(dll, name)

        assertHasSymbol(libc, "printf")
        assertHasSymbol(liblog, "__android_log_write")
        assertNotHasSymbol(libc, "__android_log_write")

        # Global search (https://bugs.python.org/issue34592): only works on newer API levels.
        if API_LEVEL >= 21:
            main = ctypes.CDLL(None)
            assertHasSymbol(main, "printf")
            assertHasSymbol(main, "__android_log_write")
            assertNotHasSymbol(main, "nonexistent")

        assertHasSymbol(ctypes.pythonapi, "PyObject_Str") 
Example #2
Source File: bgl_ext.py    From addon_common with GNU General Public License v3.0 6 votes vote down vote up
def np_array_as_bgl_Buffer(array):
    type = array.dtype
    if   type == np.int8:    type = bgl.GL_BYTE
    elif type == np.int16:   type = bgl.GL_SHORT
    elif type == np.int32:   type = bgl.GL_INT
    elif type == np.float32: type = bgl.GL_FLOAT
    elif type == np.float64: type = bgl.GL_DOUBLE
    else: raise

    _decref = ctypes.pythonapi.Py_DecRef
    _incref = ctypes.pythonapi.Py_IncRef

    _decref.argtypes = _incref.argtypes = [ctypes.py_object]
    _decref.restype = _incref.restype = None

    buf = bgl.Buffer(bgl.GL_BYTE, (1, *array.shape))[0]
    c_buf = C_Buffer.from_address(id(buf))

    _decref(c_buf.parent)
    _incref(array)

    c_buf.parent = array # Prevents MEM_freeN
    c_buf.type = type
    c_buf.buf = array.ctypes.data
    return buf 
Example #3
Source File: request_state_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.mox = mox.Mox()
    self.mox.StubOutWithMock(ctypes.pythonapi, 'PyThreadState_SetAsyncExc')
    self.request_state = request_state.RequestState('id') 
Example #4
Source File: request_state_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def test_inject_exception(self):
    ctypes.pythonapi.PyThreadState_SetAsyncExc(
        CtypesComparator(ctypes.c_long(threading.current_thread().ident)),
        CtypesComparator(ctypes.py_object(Exception)))
    self.mox.ReplayAll()
    self.request_state.inject_exception(Exception)
    self.mox.VerifyAll() 
Example #5
Source File: container.py    From benchexec with Apache License 2.0 5 votes vote down vote up
def _python_clone_child_callback(func_p):
    """Used as callback for clone, calls the passed function pointer."""
    # Strictly speaking, PyOS_AfterFork_Child should be called immediately after
    # clone calls our callback before executing any Python code because the
    # interpreter state is inconsistent, but here we are already in the Python
    # world, so it could be too late. For more information cf. execute_in_namespace()
    # and https://github.com/sosy-lab/benchexec/issues/435.
    # Thus we use this function only as fallback of architectures where we have no
    # native callback. For benchexec we combine it with the sys.setswitchinterval()
    # workaround in localexecution.py. Other users of ContainerExecutor should be safe
    # as long as they do not use many threads. We cannot do anything before cloning
    # because it might be too late anyway (gil_drop_request could be set already).
    ctypes.pythonapi.PyOS_AfterFork_Child()

    return _CLONE_NESTED_CALLBACK(func_p)() 
Example #6
Source File: inputhook.py    From Computable with MIT License 5 votes vote down vote up
def get_pyos_inputhook(self):
        """Return the current PyOS_InputHook as a ctypes.c_void_p."""
        return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook") 
Example #7
Source File: inputhook.py    From Computable with MIT License 5 votes vote down vote up
def get_pyos_inputhook_as_func(self):
        """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
        return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook") 
Example #8
Source File: collector_hypervisor.py    From opsbro with MIT License 5 votes vote down vote up
def __del__(self):
        if is_windows:
            self.win.VirtualFree(self.addr, 0, 0x8000)
        elif ctypes.pythonapi:
            # Seems to throw exception when the program ends and
            # pythonapi is cleaned up before the object?
            ctypes.pythonapi.free.restype = None
            ctypes.pythonapi.free.argtypes = [c_void_p]
            ctypes.pythonapi.free(self.addr) 
Example #9
Source File: request_state_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.mox = mox.Mox()
    self.mox.StubOutWithMock(ctypes.pythonapi, 'PyThreadState_SetAsyncExc')
    self.request_state = request_state.RequestState('id') 
Example #10
Source File: request_state_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def test_inject_exception(self):
    ctypes.pythonapi.PyThreadState_SetAsyncExc(
        CtypesComparator(ctypes.c_long(threading.current_thread().ident)),
        CtypesComparator(ctypes.py_object(Exception)))
    self.mox.ReplayAll()
    self.request_state.inject_exception(Exception)
    self.mox.VerifyAll() 
Example #11
Source File: rlwrap.py    From aioconsole with GNU General Public License v3.0 5 votes vote down vote up
def input(prompt="", use_stderr=False):
    # Use readline if possible
    try:
        import readline  # noqa
    except ImportError:
        return builtins.input(prompt)
    # Use stdout
    if not use_stderr:
        return builtins.input(prompt)
    api = ctypes.pythonapi
    # Cross-platform compatibility
    if compat.platform == "darwin":
        stdin = "__stdinp"
        stderr = "__stderrp"
    else:
        stdin = "stdin"
        stderr = "stderr"
    # Get standard streams
    try:
        fin = ctypes.c_void_p.in_dll(api, stdin)
        ferr = ctypes.c_void_p.in_dll(api, stderr)
    # Cygwin fallback
    except ValueError:
        return builtins.input(prompt)
    # Call readline
    call_readline = api.PyOS_Readline
    call_readline.restype = ctypes.c_char_p
    result = call_readline(fin, ferr, prompt.encode())
    # Decode result
    if len(result) == 0:
        raise EOFError
    return result.decode().rstrip("\n") 
Example #12
Source File: _tblib.py    From satori with Apache License 2.0 4 votes vote down vote up
def _init_ugly_crap():
    """This function implements a few ugly things so that we can patch the
    traceback objects.  The function returned allows resetting `tb_next` on
    any python traceback object.  Do not attempt to use this on non cpython
    interpreters
    """
    import ctypes
    from types import TracebackType

    # figure out side of _Py_ssize_t
    if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
        _Py_ssize_t = ctypes.c_int64
    else:
        _Py_ssize_t = ctypes.c_int

    # regular python
    class _PyObject(ctypes.Structure):
        pass
    _PyObject._fields_ = [
        ('ob_refcnt', _Py_ssize_t),
        ('ob_type', ctypes.POINTER(_PyObject))
    ]

    # python with trace
    if hasattr(sys, 'getobjects'):
        class _PyObject(ctypes.Structure):
            pass
        _PyObject._fields_ = [
            ('_ob_next', ctypes.POINTER(_PyObject)),
            ('_ob_prev', ctypes.POINTER(_PyObject)),
            ('ob_refcnt', _Py_ssize_t),
            ('ob_type', ctypes.POINTER(_PyObject))
        ]

    class _Traceback(_PyObject):
        pass
    _Traceback._fields_ = [
        ('tb_next', ctypes.POINTER(_Traceback)),
        ('tb_frame', ctypes.POINTER(_PyObject)),
        ('tb_lasti', ctypes.c_int),
        ('tb_lineno', ctypes.c_int)
    ]

    def tb_set_next(tb, next):
        """Set the tb_next attribute of a traceback object."""
        if not (isinstance(tb, TracebackType) and
                (next is None or isinstance(next, TracebackType))):
            raise TypeError('tb_set_next arguments must be traceback objects')
        obj = _Traceback.from_address(id(tb))
        if tb.tb_next is not None:
            old = _Traceback.from_address(id(tb.tb_next))
            old.ob_refcnt -= 1
        if next is None:
            obj.tb_next = ctypes.POINTER(_Traceback)()
        else:
            next = _Traceback.from_address(id(next))
            next.ob_refcnt += 1
            obj.tb_next = ctypes.pointer(next)

    return tb_set_next 
Example #13
Source File: collector_hypervisor.py    From opsbro with MIT License 4 votes vote down vote up
def __init__(self):
        if platform.machine() not in ("AMD64", "x86_64", "x86", "i686"):
            raise SystemError("Only available for x86")
        
        if is_windows:
            if is_64bit:
                # VirtualAlloc seems to fail under some weird
                # circumstances when ctypes.windll.kernel32 is
                # used under 64 bit Python. CDLL fixes this.
                self.win = ctypes.CDLL("kernel32.dll")
                opc = _WINDOWS_64_OPC
            else:
                # Here ctypes.windll.kernel32 is needed to get the
                # right DLL. Otherwise it will fail when running
                # 32 bit Python on 64 bit Windows.
                self.win = ctypes.windll.kernel32
                opc = _CDECL_32_OPC
        else:
            opc = _POSIX_64_OPC if is_64bit else _CDECL_32_OPC
        
        size = len(opc)
        code = (ctypes.c_ubyte * size)(*opc)
        
        self.r = CPUID_struct()
        
        if is_windows:
            self.addr = self.win.VirtualAlloc(None, size, 0x1000, 0x40)
            if not self.addr:
                raise MemoryError("Could not allocate RWX memory")
        else:
            ctypes.pythonapi.valloc.restype = ctypes.c_void_p
            ctypes.pythonapi.valloc.argtypes = [ctypes.c_size_t]
            self.addr = ctypes.pythonapi.valloc(size)
            if not self.addr:
                raise MemoryError("Could not allocate memory")
            
            ctypes.pythonapi.mprotect.restype = c_int
            ctypes.pythonapi.mprotect.argtypes = [c_void_p, c_size_t, c_int]
            ret = ctypes.pythonapi.mprotect(self.addr, size, 1 | 2 | 4)
            if ret != 0:
                raise OSError("Failed to set RWX")
        
        ctypes.memmove(self.addr, code, size)
        
        func_type = CFUNCTYPE(None, POINTER(CPUID_struct), c_uint32)
        self.func_ptr = func_type(self.addr) 
Example #14
Source File: _tblib.py    From PokemonGo-DesktopMap with MIT License 4 votes vote down vote up
def _init_ugly_crap():
    """This function implements a few ugly things so that we can patch the
    traceback objects.  The function returned allows resetting `tb_next` on
    any python traceback object.  Do not attempt to use this on non cpython
    interpreters
    """
    import ctypes
    from types import TracebackType

    # figure out side of _Py_ssize_t
    if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
        _Py_ssize_t = ctypes.c_int64
    else:
        _Py_ssize_t = ctypes.c_int

    # regular python
    class _PyObject(ctypes.Structure):
        pass
    _PyObject._fields_ = [
        ('ob_refcnt', _Py_ssize_t),
        ('ob_type', ctypes.POINTER(_PyObject))
    ]

    # python with trace
    if hasattr(sys, 'getobjects'):
        class _PyObject(ctypes.Structure):
            pass
        _PyObject._fields_ = [
            ('_ob_next', ctypes.POINTER(_PyObject)),
            ('_ob_prev', ctypes.POINTER(_PyObject)),
            ('ob_refcnt', _Py_ssize_t),
            ('ob_type', ctypes.POINTER(_PyObject))
        ]

    class _Traceback(_PyObject):
        pass
    _Traceback._fields_ = [
        ('tb_next', ctypes.POINTER(_Traceback)),
        ('tb_frame', ctypes.POINTER(_PyObject)),
        ('tb_lasti', ctypes.c_int),
        ('tb_lineno', ctypes.c_int)
    ]

    def tb_set_next(tb, next):
        """Set the tb_next attribute of a traceback object."""
        if not (isinstance(tb, TracebackType) and
                (next is None or isinstance(next, TracebackType))):
            raise TypeError('tb_set_next arguments must be traceback objects')
        obj = _Traceback.from_address(id(tb))
        if tb.tb_next is not None:
            old = _Traceback.from_address(id(tb.tb_next))
            old.ob_refcnt -= 1
        if next is None:
            obj.tb_next = ctypes.POINTER(_Traceback)()
        else:
            next = _Traceback.from_address(id(next))
            next.ob_refcnt += 1
            obj.tb_next = ctypes.pointer(next)

    return tb_set_next 
Example #15
Source File: _tblib.py    From PokemonGo-DesktopMap with MIT License 4 votes vote down vote up
def _init_ugly_crap():
    """This function implements a few ugly things so that we can patch the
    traceback objects.  The function returned allows resetting `tb_next` on
    any python traceback object.  Do not attempt to use this on non cpython
    interpreters
    """
    import ctypes
    from types import TracebackType

    # figure out side of _Py_ssize_t
    if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
        _Py_ssize_t = ctypes.c_int64
    else:
        _Py_ssize_t = ctypes.c_int

    # regular python
    class _PyObject(ctypes.Structure):
        pass
    _PyObject._fields_ = [
        ('ob_refcnt', _Py_ssize_t),
        ('ob_type', ctypes.POINTER(_PyObject))
    ]

    # python with trace
    if hasattr(sys, 'getobjects'):
        class _PyObject(ctypes.Structure):
            pass
        _PyObject._fields_ = [
            ('_ob_next', ctypes.POINTER(_PyObject)),
            ('_ob_prev', ctypes.POINTER(_PyObject)),
            ('ob_refcnt', _Py_ssize_t),
            ('ob_type', ctypes.POINTER(_PyObject))
        ]

    class _Traceback(_PyObject):
        pass
    _Traceback._fields_ = [
        ('tb_next', ctypes.POINTER(_Traceback)),
        ('tb_frame', ctypes.POINTER(_PyObject)),
        ('tb_lasti', ctypes.c_int),
        ('tb_lineno', ctypes.c_int)
    ]

    def tb_set_next(tb, next):
        """Set the tb_next attribute of a traceback object."""
        if not (isinstance(tb, TracebackType) and
                (next is None or isinstance(next, TracebackType))):
            raise TypeError('tb_set_next arguments must be traceback objects')
        obj = _Traceback.from_address(id(tb))
        if tb.tb_next is not None:
            old = _Traceback.from_address(id(tb.tb_next))
            old.ob_refcnt -= 1
        if next is None:
            obj.tb_next = ctypes.POINTER(_Traceback)()
        else:
            next = _Traceback.from_address(id(next))
            next.ob_refcnt += 1
            obj.tb_next = ctypes.pointer(next)

    return tb_set_next