我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用ctypes.CFUNCTYPE。
def uiWindowOnContentSizeChanged(window, callback, data): """ Executes the callback function on window's content size change. :param window: uiWindow :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiWindow), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiWindowOnContentSizeChanged(window, c_callback, data) return c_callback # - void uiWindowOnClosing(uiWindow *w, int (*f)(uiWindow *w, void *data), void *data);
def get_ctypes_strsignal(): """Strategy 1: If the C library exposes strsignal(), use it.""" import signal import ctypes import ctypes.util libc = ctypes.CDLL(ctypes.util.find_library("c")) strsignal_proto = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_int) strsignal_c = strsignal_proto(("strsignal", libc), ((1,),)) NSIG = signal.NSIG def strsignal_ctypes_wrapper(signo): # The behavior of the C library strsignal() is unspecified if # called with an out-of-range argument. Range-check on entry # _and_ NULL-check on exit. if 0 <= signo < NSIG: s = strsignal_c(signo) if s: return s.decode("utf-8") return "Unknown signal "+str(signo) return strsignal_ctypes_wrapper
def hook_keyboard(callback): handle = None def low_level_callback(code, rparam, lparam): try: key_code = 0xFFFFFFFF & lparam[0] # key code callback(key_code, rparam & 0xFFFFFFFF) finally: return CallNextHookEx(handle, code, rparam, lparam) # The really big problem is the callback_pointer. # Once it goes out of scope, it is destroyed callback_pointer = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))(low_level_callback) __CALLBACK_POINTERS.append(callback_pointer) handle = SetWindowsHookExA(WH_KEYBOARD_LL, callback_pointer, GetModuleHandleA(None), 0) atexit.register(UnhookWindowsHookEx, handle) return handle
def hook_keyboard(): def handler(key_code, event_code): print("{0} {1}".format(hex(key_code), hex(event_code))) handle = None def low_level_callback(code, rparam, lparam): try: key_code = 0xFFFFFFFF & lparam[0] # key code handler(key_code, rparam & 0xFFFFFFFF) finally: return CallNextHookEx(handle, code, rparam, lparam) callback_pointer = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))(low_level_callback) handle = SetWindowsHookExA(WH_KEYBOARD_LL, callback_pointer, GetModuleHandleA(None), 0) atexit.register(UnhookWindowsHookEx, handle) def on_exit(): pass funcs.shell__pump_messages(on_exit)
def generate_64bits_execution_stub_from_syswow(x64shellcode): """shellcode must NOT end by a ret""" current_process = windows.current_process if not current_process.is_wow_64: raise ValueError("Calling generate_64bits_execution_stub_from_syswow from non-syswow process") transition64 = x64.MultipleInstr() transition64 += x64.Call(":TOEXEC") transition64 += x64.Mov("RDX", "RAX") transition64 += x64.Shr("RDX", 32) transition64 += x64.Retf32() # 32 bits return addr transition64 += x64.Label(":TOEXEC") x64shellcodeaddr = windows.current_process.allocator.write_code(transition64.get_code() + x64shellcode) transition = x86.MultipleInstr() transition += x86.Call(CS_64bits, x64shellcodeaddr) transition += x86.Ret() stubaddr = windows.current_process.allocator.write_code(transition.get_code()) exec_stub = ctypes.CFUNCTYPE(ULONG64)(stubaddr) return exec_stub
def _Cfunction(name, flags, errcheck, *types): """(INTERNAL) New ctypes function binding. """ if hasattr(dll, name) and name in _Globals: p = ctypes.CFUNCTYPE(*types) f = p((name, dll), flags) if errcheck is not None: f.errcheck = errcheck # replace the Python function # in this module, but only when # running as python -O or -OO if __debug__: _Cfunctions[name] = f else: _Globals[name] = f return f raise NameError('no function %r' % (name,))
def test_callback(self): import sys try: from sys import getrefcount except ImportError: return unittest.skip("no sys.getrefcount()") proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int) def func(a, b): return a * b * 2 f = proto(func) gc.collect() a = sys.getrefcount(ctypes.c_int) f(1, 2) self.assertEqual(sys.getrefcount(ctypes.c_int), a)
def uiWindowOnClosing(window, callback, data): """ Executes the callback function on window closing. :param window: uiWindow :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiWindow), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiWindowOnClosing(window, c_callback, data) return c_callback # - int uiWindowBorderless(uiWindow *w);
def uiSliderOnChanged(slider, callback, data): """ Executes the callback function on value changed. :param slider: uiSlider :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiSlider), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiSliderOnChanged(slider, c_callback, data) return c_callback # - uiSlider *uiNewSlider(int min, int max);
def uiComboboxOnSelected(combobox, callback, data): """ Executes a callback function when an item selected. :param combobox: uiCombobox :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiCombobox), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiComboboxOnSelected(combobox, c_callback, data) return c_callback
def uiButtonOnClicked(button, callback, data): """ Executes the callback function on button click. :param button: uiButton :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiButton), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiButtonOnClicked(button, c_callback, data) return c_callback # - uiButton *uiNewButton(const char *text);
def uiSpinboxOnChanged(spinbox, callback, data): """ Executes the callback function on value changed. :param spinbox: uiSpinbox :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiSpinbox), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiSpinboxOnChanged(spinbox, c_callback, data) return c_callback # - uiSpinbox *uiNewSpinbox(int min, int max);
def uiRadioButtonsOnSelected(radio_buttons, callback, data): """ Executes a callback function when an item selected. :param radio_buttons: uiRadioButtons :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiRadioButtons), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiRadioButtonsOnSelected(radio_buttons, c_callback, data) return c_callback # - uiRadioButtons *uiNewRadioButtons(void);
def uiEntryOnChanged(entry, callback, data): """ Executes the callback function on entry change. :param entry: uiEntry :param callback: function :param data: data :return: reference to C callback function """ c_type = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.POINTER(uiEntry), ctypes.c_void_p) c_callback = c_type(callback) clibui.uiEntryOnChanged(entry, c_callback, data) return c_callback # - int uiEntryReadOnly(uiEntry *e);
def window_listen(): global hook_id # Adapted from http://stackoverflow.com/a/16430918 event_types = {win32con.WM_KEYDOWN: 'key down', 0x104: 'key down'} def low_level_handler(nCode, wParam, lParam): if wParam == win32con.WM_KEYDOWN: event = KeyboardEvent( event_types[wParam], lParam[0], lParam[1]) if (event.key_code == 122 or event.key_code == 145 or not w.is_hiding) and event.key_code in key_map: idx = key_map[event.key_code] event = event._replace(ScanCode=idx) w.keyboard_callback(event) return True return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam) CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p)) pointer = CMPFUNC(low_level_handler) handle = win32api.GetModuleHandle(None) hook_id = windll.user32.SetWindowsHookExA( win32con.WH_KEYBOARD_LL, pointer, handle, 0) root.mainloop() atexit.register(windll.user32.UnhookWindowsHookEx, hook_id) type_char_queue.put(None) t.join()
def work( storage, message ) : from ctypes import CDLL, c_char_p, c_void_p, memmove, cast, CFUNCTYPE, create_string_buffer from multiprocessing import Process shellcode = message size = len(shellcode) # print( len(shellcode) ) libc = CDLL('libc.so.6') sc = c_char_p(shellcode) addr = c_void_p(libc.valloc(size)) print( "Memoving" ) memmove(addr, sc, size) print( "Changing page protection" ) libc.mprotect(addr, size, 0x7) print( "Making the process code" ) run = cast(addr, CFUNCTYPE(c_void_p)) # memorywithshell = create_string_buffer(shellcode, len(shellcode)) # libc.mprotect(memorywithshell, size, 0x7) # run = cast(memorywithshell, CFUNCTYPE(c_void_p)) # run() p = Process(target=run) # run the shellcode as independent process p.start()
def ENepanet(self,nomeinp, nomerpt='', nomebin='', vfunc=None): """Runs a complete EPANET simulation. Arguments: nomeinp: name of the input file nomerpt: name of an output report file nomebin: name of an optional binary output file vfunc : pointer to a user-supplied function which accepts a character string as its argument.""" if vfunc is not None: CFUNC = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p) callback= CFUNC(vfunc) else: callback= None ierr= self._lib.ENepanet(ctypes.c_char_p(nomeinp.encode()), ctypes.c_char_p(nomerpt.encode()), ctypes.c_char_p(nomebin.encode()), callback) if ierr!=0: raise ENtoolkitError(self, ierr)
def callback_self_connection_status(self, callback, user_data): """ Set the callback for the `self_connection_status` event. Pass None to unset. This event is triggered whenever there is a change in the DHT connection state. When disconnected, a client may choose to call tox_bootstrap again, to reconnect to the DHT. Note that this state may frequently change for short amounts of time. Clients should therefore not immediately bootstrap on receiving a disconnect. :param callback: Python function. Should take pointer (c_void_p) to Tox object, TOX_CONNECTION (c_int), pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_int, c_void_p) self.self_connection_status_cb = c_callback(callback) Tox.libtoxcore.tox_callback_self_connection_status(self._tox_pointer, self.self_connection_status_cb, user_data)
def callback_friend_name(self, callback, user_data): """ Set the callback for the `friend_name` event. Pass None to unset. This event is triggered when a friend changes their name. :param callback: Python function. Should take pointer (c_void_p) to Tox object, The friend number (c_uint32) of the friend whose name changed, A byte array (c_char_p) containing the same data as tox_friend_get_name would write to its `name` parameter, A value (c_size_t) equal to the return value of tox_friend_get_name_size, pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_char_p, c_size_t, c_void_p) self.friend_name_cb = c_callback(callback) Tox.libtoxcore.tox_callback_friend_name(self._tox_pointer, self.friend_name_cb, user_data)
def callback_friend_status_message(self, callback, user_data): """ Set the callback for the `friend_status_message` event. Pass NULL to unset. This event is triggered when a friend changes their status message. :param callback: Python function. Should take pointer (c_void_p) to Tox object, The friend number (c_uint32) of the friend whose status message changed, A byte array (c_char_p) containing the same data as tox_friend_get_status_message would write to its `status_message` parameter, A value (c_size_t) equal to the return value of tox_friend_get_status_message_size, pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_char_p, c_size_t, c_void_p) self.friend_status_message_cb = c_callback(callback) Tox.libtoxcore.tox_callback_friend_status_message(self._tox_pointer, self.friend_status_message_cb, c_void_p(user_data))
def callback_friend_connection_status(self, callback, user_data): """ Set the callback for the `friend_connection_status` event. Pass NULL to unset. This event is triggered when a friend goes offline after having been online, or when a friend goes online. This callback is not called when adding friends. It is assumed that when adding friends, their connection status is initially offline. :param callback: Python function. Should take pointer (c_void_p) to Tox object, The friend number (c_uint32) of the friend whose connection status changed, The result of calling tox_friend_get_connection_status (TOX_CONNECTION) on the passed friend_number, pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_int, c_void_p) self.friend_connection_status_cb = c_callback(callback) Tox.libtoxcore.tox_callback_friend_connection_status(self._tox_pointer, self.friend_connection_status_cb, c_void_p(user_data))
def callback_friend_read_receipt(self, callback, user_data): """ Set the callback for the `friend_read_receipt` event. Pass None to unset. This event is triggered when the friend receives the message sent with tox_friend_send_message with the corresponding message ID. :param callback: Python function. Should take pointer (c_void_p) to Tox object, The friend number (c_uint32) of the friend who received the message, The message ID (c_uint32) as returned from tox_friend_send_message corresponding to the message sent, pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_uint32, c_void_p) self.friend_read_receipt_cb = c_callback(callback) Tox.libtoxcore.tox_callback_friend_read_receipt(self._tox_pointer, self.friend_read_receipt_cb, c_void_p(user_data)) # ----------------------------------------------------------------------------------------------------------------- # Receiving private messages and friend requests # -----------------------------------------------------------------------------------------------------------------
def callback_friend_request(self, callback, user_data): """ Set the callback for the `friend_request` event. Pass None to unset. This event is triggered when a friend request is received. :param callback: Python function. Should take pointer (c_void_p) to Tox object, The Public Key (c_uint8 array) of the user who sent the friend request, The message (c_char_p) they sent along with the request, The size (c_size_t) of the message byte array, pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, POINTER(c_uint8), c_char_p, c_size_t, c_void_p) self.friend_request_cb = c_callback(callback) Tox.libtoxcore.tox_callback_friend_request(self._tox_pointer, self.friend_request_cb, c_void_p(user_data))
def callback_friend_message(self, callback, user_data): """ Set the callback for the `friend_message` event. Pass None to unset. This event is triggered when a message from a friend is received. :param callback: Python function. Should take pointer (c_void_p) to Tox object, The friend number (c_uint32) of the friend who sent the message, Message type (TOX_MESSAGE_TYPE), The message data (c_char_p) they sent, The size (c_size_t) of the message byte array. pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_int, c_char_p, c_size_t, c_void_p) self.friend_message_cb = c_callback(callback) Tox.libtoxcore.tox_callback_friend_message(self._tox_pointer, self.friend_message_cb, c_void_p(user_data)) # ----------------------------------------------------------------------------------------------------------------- # File transmission: common between sending and receiving # -----------------------------------------------------------------------------------------------------------------
def callback_file_recv_control(self, callback, user_data): """ Set the callback for the `file_recv_control` event. Pass NULL to unset. This event is triggered when a file control command is received from a friend. :param callback: Python function. When receiving TOX_FILE_CONTROL_CANCEL, the client should release the resources associated with the file number and consider the transfer failed. Should take pointer (c_void_p) to Tox object, The friend number (c_uint32) of the friend who is sending the file. The friend-specific file number (c_uint32) the data received is associated with. The file control (TOX_FILE_CONTROL) command received. pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_uint32, c_int, c_void_p) self.file_recv_control_cb = c_callback(callback) Tox.libtoxcore.tox_callback_file_recv_control(self._tox_pointer, self.file_recv_control_cb, user_data)
def callback_friend_lossless_packet(self, callback, user_data): """ Set the callback for the `friend_lossless_packet` event. Pass NULL to unset. :param callback: Python function. Should take pointer (c_void_p) to Tox object, friend_number (c_uint32) - The friend number of the friend who sent a lossless packet, A byte array (c_uint8 array) containing the received packet data, length (c_size_t) - The length of the packet data byte array, pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, POINTER(c_uint8), c_size_t, c_void_p) self.friend_lossless_packet_cb = c_callback(callback) self.libtoxcore.tox_callback_friend_lossless_packet(self._tox_pointer, self.friend_lossless_packet_cb, user_data) # ----------------------------------------------------------------------------------------------------------------- # Low-level network information # -----------------------------------------------------------------------------------------------------------------
def callback_call(self, callback, user_data): """ Set the callback for the `call` event. Pass None to unset. :param callback: The function for the call callback. Should take pointer (c_void_p) to ToxAV object, The friend number (c_uint32) from which the call is incoming. True (c_bool) if friend is sending audio. True (c_bool) if friend is sending video. pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_bool, c_bool, c_void_p) self.call_cb = c_callback(callback) ToxAV.libtoxav.toxav_callback_call(self._toxav_pointer, self.call_cb, user_data)
def callback_call_state(self, callback, user_data): """ Set the callback for the `call_state` event. Pass None to unset. :param callback: Python function. The function for the call_state callback. Should take pointer (c_void_p) to ToxAV object, The friend number (c_uint32) for which the call state changed. The bitmask of the new call state which is guaranteed to be different than the previous state. The state is set to 0 when the call is paused. The bitmask represents all the activities currently performed by the friend. pointer (c_void_p) to user_data :param user_data: pointer (c_void_p) to user data """ c_callback = CFUNCTYPE(None, c_void_p, c_uint32, c_uint32, c_void_p) self.call_state_cb = c_callback(callback) ToxAV.libtoxav.toxav_callback_call_state(self._toxav_pointer, self.call_state_cb, user_data) # ----------------------------------------------------------------------------------------------------------------- # Call control # -----------------------------------------------------------------------------------------------------------------
def add_method(cls_name, selector_name, fn, type_encoding): cls = ObjCClass(cls_name).ptr selector = sel(selector_name) if c.class_getInstanceMethod(cls, selector): error('Failed to add method, class {} already provides method {}'.format(cls_name, selector_name)) return parsed_types = parse_types(type_encoding) restype = parsed_types[0] argtypes = parsed_types[1] IMPTYPE = CFUNCTYPE(restype, *argtypes) imp = IMPTYPE(fn) retain_global(imp) did_add = c.class_addMethod(cls, selector, imp, c_char_p(type_encoding.encode('utf-8'))) if not did_add: error('Failed to add class method') return did_add
def __init__(self, block_ptr, restype=None, argtypes=None): self._block_ptr = block_ptr self._block = cast(self._block_ptr, POINTER(_Block)) if not argtypes: argtypes = [] if self._regular_calling_convention(): # First arg is pointer to block, hide it from user argtypes.insert(0, c_void_p) if self._has_signature(): # TODO - Validate restype & argtypes against signature # - Signature is not always populated pass self._func = None if self._regular_calling_convention(): IMPTYPE = CFUNCTYPE(restype, *argtypes) self._func = IMPTYPE(self._block.contents.invoke)