本文整理汇总了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")
示例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
示例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')
示例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()
示例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)()
示例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")
示例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")
示例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)
示例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")
示例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
示例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)