當前位置: 首頁>>代碼示例>>Python>>正文


Python ctypes.pythonapi方法代碼示例

本文整理匯總了Python中ctypes.pythonapi方法的典型用法代碼示例。如果您正苦於以下問題:Python ctypes.pythonapi方法的具體用法?Python ctypes.pythonapi怎麽用?Python ctypes.pythonapi使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ctypes的用法示例。


在下文中一共展示了ctypes.pythonapi方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_ctypes

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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") 
開發者ID:chaquo,項目名稱:chaquopy,代碼行數:27,代碼來源:test_android.py

示例2: np_array_as_bgl_Buffer

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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 
開發者ID:CGCookie,項目名稱:addon_common,代碼行數:27,代碼來源:bgl_ext.py

示例3: setUp

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
def setUp(self):
    self.mox = mox.Mox()
    self.mox.StubOutWithMock(ctypes.pythonapi, 'PyThreadState_SetAsyncExc')
    self.request_state = request_state.RequestState('id') 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:6,代碼來源:request_state_test.py

示例4: test_inject_exception

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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() 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:9,代碼來源:request_state_test.py

示例5: _python_clone_child_callback

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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)() 
開發者ID:sosy-lab,項目名稱:benchexec,代碼行數:17,代碼來源:container.py

示例6: get_pyos_inputhook

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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") 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:5,代碼來源:inputhook.py

示例7: get_pyos_inputhook_as_func

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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") 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:5,代碼來源:inputhook.py

示例8: __del__

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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) 
開發者ID:naparuba,項目名稱:opsbro,代碼行數:11,代碼來源:collector_hypervisor.py

示例9: input

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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") 
開發者ID:vxgmichel,項目名稱:aioconsole,代碼行數:34,代碼來源:rlwrap.py

示例10: _init_ugly_crap

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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 
開發者ID:leancloud,項目名稱:satori,代碼行數:62,代碼來源:_tblib.py

示例11: __init__

# 需要導入模塊: import ctypes [as 別名]
# 或者: from ctypes import pythonapi [as 別名]
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) 
開發者ID:naparuba,項目名稱:opsbro,代碼行數:48,代碼來源:collector_hypervisor.py


注:本文中的ctypes.pythonapi方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。