Python ctypes.py_object() Examples
The following are 30
code examples of ctypes.py_object().
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: crypto.py From privacyidea with GNU Affero General Public License v3.0 | 7 votes |
def zerome(bufferObject): ''' clear a string value from memory :param bufferObject: the string variable, which should be cleared :type bufferObject: string or key buffer :return: - nothing - ''' data = ctypes.POINTER(ctypes.c_char)() size = ctypes.c_int() # Note, int only valid for python 2.5 ctypes.pythonapi.PyObject_AsCharBuffer(ctypes.py_object(bufferObject), ctypes.pointer(data), ctypes.pointer(size)) ctypes.memset(data, 0, size.value) return
Example #2
Source File: debug.py From pipenv with MIT License | 6 votes |
def tb_set_next(tb, tb_next): c_tb = _CTraceback.from_address(id(tb)) # Clear out the old tb_next. if tb.tb_next is not None: c_tb_next = ctypes.py_object(tb.tb_next) c_tb.tb_next = ctypes.py_object() ctypes.pythonapi.Py_DecRef(c_tb_next) # Assign the new tb_next. if tb_next is not None: c_tb_next = ctypes.py_object(tb_next) ctypes.pythonapi.Py_IncRef(c_tb_next) c_tb.tb_next = c_tb_next return tb
Example #3
Source File: qtcef.py From Librian with Mozilla Public License 2.0 | 6 votes |
def getHandle(self): if self.hidden_window: # PyQt5 on Linux return int(self.hidden_window.winId()) try: # PyQt4 and PyQt5 return int(self.winId()) except: # PySide: # | QWidget.winId() returns <PyCObject object at 0x02FD8788> # | Converting it to int using ctypes. ctypes.pythonapi.PyCapsule_GetPointer.restype = (ctypes.c_void_p) ctypes.pythonapi.PyCapsule_GetPointer.argtypes = ([ ctypes.py_object ]) return ctypes.pythonapi.PyCapsule_GetPointer(self.winId(), None)
Example #4
Source File: base_cdm_dbg.py From codimension with GNU General Public License v3.0 | 6 votes |
def storeFrameLocals(self, frmnr=0): """Stores the locals into the frame. Thus an access to frame.f_locals returns the last data """ cf = self.currentFrame while cf is not None and frmnr > 0: cf = cf.f_back frmnr -= 1 try: if '__pypy__' in sys.builtin_module_names: import __pypy__ __pypy__.locals_to_fast(cf) return except Exception: pass ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(cf), ctypes.c_int(0))
Example #5
Source File: killthread.py From mishkal with GNU General Public License v3.0 | 6 votes |
def async_raise(tid, exctype): """raises the exception, performs cleanup if needed. tid is the value given by thread.get_ident() (an integer). Raise SystemExit to kill a thread.""" if not isinstance(exctype, (types.ClassType, type)): raise TypeError("Only types can be raised (not instances)") if not isinstance(tid, int): raise TypeError("tid must be an integer") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed")
Example #6
Source File: cloudpickle.py From spark-cluster-deployment with Apache License 2.0 | 6 votes |
def _make_skel_func(code, num_closures, base_globals = None): """ Creates a skeleton function object that contains just the provided code and the correct number of cells in func_closure. All other func attributes (e.g. func_globals) are empty. """ #build closure (cells): if not ctypes: raise Exception('ctypes failed to import; cannot build function') cellnew = ctypes.pythonapi.PyCell_New cellnew.restype = ctypes.py_object cellnew.argtypes = (ctypes.py_object,) dummy_closure = tuple(map(lambda i: cellnew(None), range(num_closures))) if base_globals is None: base_globals = {} base_globals['__builtins__'] = __builtins__ return types.FunctionType(code, base_globals, None, None, dummy_closure) # this piece of opaque code is needed below to modify 'cell' contents
Example #7
Source File: threadstop.py From stopit with MIT License | 6 votes |
def async_raise(target_tid, exception): """Raises an asynchronous exception in another thread. Read http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc for further enlightenments. :param target_tid: target thread identifier :param exception: Exception class to be raised in that thread """ # Ensuring and releasing GIL are useless since we're not in C # gil_state = ctypes.pythonapi.PyGILState_Ensure() ret = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(target_tid), ctypes.py_object(exception)) # ctypes.pythonapi.PyGILState_Release(gil_state) if ret == 0: raise ValueError("Invalid thread ID {}".format(target_tid)) elif ret > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(target_tid), None) raise SystemError("PyThreadState_SetAsyncExc failed")
Example #8
Source File: publisher.py From sawtooth-core with Apache License 2.0 | 6 votes |
def send(self, item): res = LIBRARY.call( "incoming_batch_sender_send", self._ptr, ctypes.py_object(item)) if res == IncomingBatchSenderErrorCode.Success: return if res == IncomingBatchSenderErrorCode.NullPointerProvided: raise TypeError("Provided null pointer(s)") if res == IncomingBatchSenderErrorCode.InvalidInput: raise ValueError("Input was not valid ") if res == IncomingBatchSenderErrorCode.Disconnected: raise Disconnected() raise ValueError("An unknown error occurred: {}".format(res))
Example #9
Source File: base.py From pympress with GNU General Public License v2.0 | 6 votes |
def get_window_handle(window): """ Uses ctypes to call gdk_win32_window_get_handle which is not available in python gobject introspection porting. Solution from http://stackoverflow.com/a/27236258/1387346 Args: window (:class:`~Gdk.Window`): The window for which we want to get the handle Returns: The handle to the win32 window """ # get the c gpointer of the gdk window ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object] drawingarea_gpointer = ctypes.pythonapi.PyCapsule_GetPointer(window.__gpointer__, None) # get the win32 handle gdkdll = ctypes.CDLL('libgdk-3-0.dll') return gdkdll.gdk_win32_window_get_handle(drawingarea_gpointer)
Example #10
Source File: _compat.py From python-netsurv with MIT License | 6 votes |
def make_set_closure_cell(): """ Moved into a function for testability. """ if PYPY: # pragma: no cover def set_closure_cell(cell, value): cell.__setstate__((value,)) else: try: ctypes = import_ctypes() set_closure_cell = ctypes.pythonapi.PyCell_Set set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object) set_closure_cell.restype = ctypes.c_int except Exception: # We try best effort to set the cell, but sometimes it's not # possible. For example on Jython or on GAE. set_closure_cell = just_warn return set_closure_cell
Example #11
Source File: _compat.py From python-netsurv with MIT License | 6 votes |
def make_set_closure_cell(): """ Moved into a function for testability. """ if PYPY: # pragma: no cover def set_closure_cell(cell, value): cell.__setstate__((value,)) else: try: ctypes = import_ctypes() set_closure_cell = ctypes.pythonapi.PyCell_Set set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object) set_closure_cell.restype = ctypes.c_int except Exception: # We try best effort to set the cell, but sometimes it's not # possible. For example on Jython or on GAE. set_closure_cell = just_warn return set_closure_cell
Example #12
Source File: bgl_ext.py From addon_common with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: PlatformManagerWindows.py From lackey with MIT License | 6 votes |
def getWindowByTitle(self, wildcard, order=0): """ Returns a handle for the first window that matches the provided "wildcard" regex """ EnumWindowsProc = ctypes.WINFUNCTYPE( ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.py_object) def callback(hwnd, context): if ctypes.windll.user32.IsWindowVisible(hwnd): length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) buff = ctypes.create_unicode_buffer(length + 1) ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) if re.search(context["wildcard"], buff.value, flags=re.I) != None and not context["handle"]: if context["order"] > 0: context["order"] -= 1 else: context["handle"] = hwnd return True data = {"wildcard": wildcard, "handle": None, "order": order} ctypes.windll.user32.EnumWindows(EnumWindowsProc(callback), ctypes.py_object(data)) return data["handle"]
Example #14
Source File: PlatformManagerWindows.py From lackey with MIT License | 6 votes |
def getWindowByPID(self, pid, order=0): """ Returns a handle for the first window that matches the provided PID """ if pid <= 0: return None EnumWindowsProc = ctypes.WINFUNCTYPE( ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.py_object) def callback(hwnd, context): if ctypes.windll.user32.IsWindowVisible(hwnd): pid = ctypes.c_ulong() ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) if context["pid"] == int(pid.value) and not context["handle"]: if context["order"] > 0: context["order"] -= 1 else: context["handle"] = hwnd return True data = {"pid": pid, "handle": None, "order": order} ctypes.windll.user32.EnumWindows(EnumWindowsProc(callback), ctypes.py_object(data)) return data["handle"]
Example #15
Source File: helpers.py From ctpbee with MIT License | 5 votes |
def _async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed")
Example #16
Source File: strtree.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
def __init__(self, geoms): # filter empty geometries out of the input geoms = [geom for geom in geoms if not geom.is_empty] self._n_geoms = len(geoms) # GEOS STRtree capacity has to be > 1 self._tree_handle = lgeos.GEOSSTRtree_create(max(2, len(geoms))) for geom in geoms: lgeos.GEOSSTRtree_insert(self._tree_handle, geom._geom, ctypes.py_object(geom))
Example #17
Source File: exec_timeout.py From agents-aea with Apache License 2.0 | 5 votes |
def _set_thread_exception(thread_id: int, exception_class: Type[Exception]) -> None: """ Terminate code execution in specific thread by setting exception. :return: None """ ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread_id), ctypes.py_object(exception_class) )
Example #18
Source File: shthreads.py From stash with MIT License | 5 votes |
def _async_raise(self): tid = self.ident res = python_capi.PyThreadState_SetAsyncExc(ctypes.c_long(tid) if M_64 else tid, ctypes.py_object(KeyboardInterrupt)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # "if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect" python_capi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), 0) raise SystemError("PyThreadState_SetAsyncExc failed") return res
Example #19
Source File: interruptable_thread.py From dirigible-spreadsheet with MIT License | 5 votes |
def interrupt(self): if not self.isAlive(): return tid = self._get_thread_id() threads_affected = pythonapi.PyThreadState_SetAsyncExc(c_long(tid), py_object(TimeoutException)) if threads_affected != 1: # if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect pythonapi.PyThreadState_SetAsyncExc(c_long(tid), None) raise SystemError("PyThreadState_SetAsyncExc failed")
Example #20
Source File: ndarray.py From training_results_v0.6 with Apache License 2.0 | 5 votes |
def _dlpack_deleter(pycapsule): pycapsule = ctypes.cast(pycapsule, ctypes.py_object) if ctypes.pythonapi.PyCapsule_IsValid(pycapsule, _c_str_dltensor): ptr = ctypes.pythonapi.PyCapsule_GetPointer(pycapsule, _c_str_dltensor) _LIB.TVMDLManagedTensorCallDeleter(ptr) ctypes.pythonapi.PyCapsule_SetDestructor(dltensor, TVMPyCapsuleDestructor(0))
Example #21
Source File: main.py From NXP-MCUBootUtility with Apache License 2.0 | 5 votes |
def _async_raise(tid, exctype): tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed")
Example #22
Source File: helper.py From rssant with BSD 3-Clause "New" or "Revised" License | 5 votes |
def unsafe_kill_thread(thread_id): # https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/ if thread_id is None: return False res = ctypes.pythonapi.PyThreadState_SetAsyncExc( thread_id, ctypes.py_object(SystemExit)) if res > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) LOG.error(f'kill thread#{thread_id} failed') return res <= 0
Example #23
Source File: __init__.py From brozzler with Apache License 2.0 | 5 votes |
def thread_raise(thread, exctype): ''' Raises or queues the exception `exctype` for the thread `thread`. See the documentation on the function `thread_exception_gate()` for more information. Adapted from http://tomerfiliba.com/recipes/Thread2/ which explains: "The exception will be raised only when executing python bytecode. If your thread calls a native/built-in blocking function, the exception will be raised only when execution returns to the python code." Raises: TypeError if `exctype` is not a class ValueError, SystemError in case of unexpected problems ''' import ctypes, inspect, threading, logging if not inspect.isclass(exctype): raise TypeError( 'cannot raise %s, only exception types can be raised (not ' 'instances)' % exctype) gate = thread_exception_gate(thread) with gate.lock: if gate.ok_to_raise.is_set() and thread.is_alive(): gate.ok_to_raise.clear() logging.info('raising %s in thread %s', exctype, thread) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread.ident), ctypes.py_object(exctype)) if res == 0: raise ValueError( 'invalid thread id? thread.ident=%s' % thread.ident) elif res != 1: # if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, 0) raise SystemError('PyThreadState_SetAsyncExc failed') else: logging.info('queueing %s for thread %s', exctype, thread) gate.queue_exception(exctype)
Example #24
Source File: visualstudio_py_debugger.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def locals_to_fast(self, frame): try: ltf = ctypes.pythonapi.PyFrame_LocalsToFast ltf.argtypes = [ctypes.py_object, ctypes.c_int] ltf(frame, 1) except: pass
Example #25
Source File: visualstudio_py_debugger.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def locals_to_fast(self, frame): try: ltf = ctypes.pythonapi.PyFrame_LocalsToFast ltf.argtypes = [ctypes.py_object, ctypes.c_int] ltf(frame, 1) except: pass
Example #26
Source File: visualstudio_py_debugger.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def locals_to_fast(self, frame): try: ltf = ctypes.pythonapi.PyFrame_LocalsToFast ltf.argtypes = [ctypes.py_object, ctypes.c_int] ltf(frame, 1) except: pass
Example #27
Source File: visualstudio_py_debugger.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def locals_to_fast(self, frame): try: ltf = ctypes.pythonapi.PyFrame_LocalsToFast ltf.argtypes = [ctypes.py_object, ctypes.c_int] ltf(frame, 1) except: pass
Example #28
Source File: PupyJob.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def _async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" if not inspect.isclass(exctype): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None) raise SystemError("PyThreadState_SetAsyncExc failed")
Example #29
Source File: PupyJob.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def _async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" if not inspect.isclass(exctype): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None) raise SystemError("PyThreadState_SetAsyncExc failed")
Example #30
Source File: strtree.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
def query(self, geom): if self._n_geoms == 0: return [] result = [] def callback(item, userdata): geom = ctypes.cast(item, ctypes.py_object).value result.append(geom) lgeos.GEOSSTRtree_query(self._tree_handle, geom._geom, lgeos.GEOSQueryCallback(callback), None) return result