Python ctypes.CFUNCTYPE Examples

The following are 30 code examples of ctypes.CFUNCTYPE(). 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: syswow64.py    From LKD with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def execute_64bits_code_from_syswow(shellcode):
    """shellcode must not end by a ret"""
    if not windows.current_process.is_wow_64:
        raise ValueError("Calling execute_64bits_code_from_syswow from non-syswow process")
    addr = windows.winproxy.VirtualAlloc(dwSize=0x1000)
    # post-exec 32bits stub (xor eax, eax; ret)
    ret = "\xC3"
    ret_addr = addr
    shell_code_addr = ret_addr + len(ret) + len(dummy_jump)
    # ljmp
    jump = "\xea" + struct.pack("<I", shell_code_addr) + chr(CS_64bits) + "\x00\x00"
    jump_addr = ret_addr + len(ret)
    # Return to 32bits stub
    shellcode += genere_return_32bits_stub(ret_addr)
    # WRITE ALL THE STUBS
    windows.current_process.write_memory(ret_addr, ret)
    windows.current_process.write_memory(jump_addr, jump)
    windows.current_process.write_memory(shell_code_addr, shellcode)
    # Execute
    exec_stub = ctypes.CFUNCTYPE(HRESULT)(jump_addr)
    return exec_stub() 
Example #2
Source File: button.py    From pylibui with MIT License 6 votes vote down vote up
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); 
Example #3
Source File: runtime.py    From blackmamba with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: runtime.py    From blackmamba with MIT License 6 votes vote down vote up
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 
Example #5
Source File: epanet2.py    From epynet with Apache License 2.0 6 votes vote down vote up
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.EN_epanet(self.ph, 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) 
Example #6
Source File: update.py    From EDMarketConnector with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, master):
            try:
                sys.frozen	# don't want to try updating python.exe
                self.updater = ctypes.cdll.WinSparkle
                self.updater.win_sparkle_set_appcast_url(update_feed)	# py2exe won't let us embed this in resources

                # set up shutdown callback
                global root
                root = master
                self.callback_t = ctypes.CFUNCTYPE(None)	# keep reference
                self.callback_fn = self.callback_t(shutdown_request)
                self.updater.win_sparkle_set_shutdown_request_callback(self.callback_fn)

                self.updater.win_sparkle_init()

            except:
                from traceback import print_exc
                print_exc()
                self.updater = None 
Example #7
Source File: slider.py    From pylibui with MIT License 6 votes vote down vote up
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); 
Example #8
Source File: combobox.py    From pylibui with MIT License 6 votes vote down vote up
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 
Example #9
Source File: checkbox.py    From pylibui with MIT License 6 votes vote down vote up
def uiCheckboxOnToggled(checkbox, callback, data):
    """
    Executes the callback function on checkbox toggle.

    :param checkbox: uiCheckbox
    :param callback: function
    :param data: data
    :return: reference to C callback function
    """
    c_type = ctypes.CFUNCTYPE(
        ctypes.c_int, ctypes.POINTER(uiCheckbox), ctypes.c_void_p)
    c_callback = c_type(callback)

    clibui.uiCheckboxOnToggled(checkbox, c_callback, data)

    return c_callback


# - int uiCheckboxChecked(uiCheckbox *c); 
Example #10
Source File: multilineentry.py    From pylibui with MIT License 6 votes vote down vote up
def uiMultilineEntryOnChanged(entry, callback, data):
    """
    Executes the callback function on multiline entry change.

    :param entry: uiMultilineEntry
    :param callback: function
    :param data: data
    :return: reference to C callback function
    """
    c_type = ctypes.CFUNCTYPE(
        ctypes.c_int, ctypes.POINTER(uiMultilineEntry), ctypes.c_void_p)
    c_callback = c_type(callback)

    clibui.uiMultilineEntryOnChanged(entry, c_callback, data)

    return c_callback


# - int uiMultilineEntryReadOnly(uiMultilineEntry *e); 
Example #11
Source File: radiobuttons.py    From pylibui with MIT License 6 votes vote down vote up
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); 
Example #12
Source File: spinbox.py    From pylibui with MIT License 6 votes vote down vote up
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); 
Example #13
Source File: window.py    From pylibui with MIT License 6 votes vote down vote up
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); 
Example #14
Source File: window.py    From pylibui with MIT License 6 votes vote down vote up
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); 
Example #15
Source File: executor.py    From mxnet-lambda with Apache License 2.0 6 votes vote down vote up
def set_monitor_callback(self, callback):
        """Install callback for monitor.

        Parameters
        ----------
        callback : function
            Takes a string and an NDArrayHandle.

        Examples
        --------
        >>> def mon_callback(*args, **kwargs):
        >>>     print("Do your stuff here.")
        >>>
        >>> texe.set_monitor_callback(mon_callback)
        """
        cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
        self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
        check_call(_LIB.MXExecutorSetMonitorCallback(
            self.handle,
            self._monitor_callback,
            None)) 
Example #16
Source File: executor.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def set_monitor_callback(self, callback):
        """Install callback for monitor.

        Parameters
        ----------
        callback : function
            Takes a string and an NDArrayHandle.

        Examples
        --------
        >>> def mon_callback(*args, **kwargs):
        >>>     print("Do your stuff here.")
        >>>
        >>> texe.set_monitor_callback(mon_callback)
        """
        cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
        self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
        check_call(_LIB.MXExecutorSetMonitorCallback(
            self.handle,
            self._monitor_callback,
            None)) 
Example #17
Source File: player.py    From clay with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.instance = vlc.Instance()
        print_func = CFUNCTYPE(c_void_p,
                               c_void_p,  # data
                               c_int,     # level
                               c_void_p,  # context
                               c_char_p,  # fmt
                               c_void_p)  # args

        self.instance.log_set(print_func(_dummy_log), None)

        self.instance.set_user_agent(
            meta.APP_NAME,
            meta.USER_AGENT
        )

        self.media_player = self.instance.media_player_new()

        self.media_player.event_manager().event_attach(
            vlc.EventType.MediaPlayerPlaying,
            self._media_state_changed
        )
        self.media_player.event_manager().event_attach(
            vlc.EventType.MediaPlayerPaused,
            self._media_state_changed
        )
        self.media_player.event_manager().event_attach(
            vlc.EventType.MediaPlayerEndReached,
            self._media_end_reached
        )
        self.media_player.event_manager().event_attach(
            vlc.EventType.MediaPlayerPositionChanged,
            self._media_position_changed
        )

        self.equalizer = vlc.libvlc_audio_equalizer_new()
        self.media_player.set_equalizer(self.equalizer)
        self._create_station_notification = None
        self._is_loading = False
        self.queue = _Queue() 
Example #18
Source File: test_refcounts.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_callback(self):
        import sys

        proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
        def func(a, b):
            return a * b * 2
        f = proto(func)

        a = sys.getrefcount(ctypes.c_int)
        f(1, 2)
        self.assertEqual(sys.getrefcount(ctypes.c_int), a) 
Example #19
Source File: client.py    From canisrufus with GNU General Public License v3.0 5 votes vote down vote up
def getFPTR(self, fn):                                                                  
        CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
        return CMPFUNC(fn) 
Example #20
Source File: test_refcounts.py    From android_universal with MIT License 5 votes vote down vote up
def test_callback(self):
        import sys

        proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
        def func(a, b):
            return a * b * 2
        f = proto(func)

        a = sys.getrefcount(ctypes.c_int)
        f(1, 2)
        self.assertEqual(sys.getrefcount(ctypes.c_int), a) 
Example #21
Source File: __init__.py    From idapkg with MIT License 5 votes vote down vote up
def _ida_lib():
    ea_name = 'ida64' if current_ea == 64 else 'ida'
    if current_os == 'win':
        functype = ctypes.WINFUNCTYPE
        lib = getattr(ctypes.windll, ea_name)
    elif current_os == 'mac':
        functype = ctypes.CFUNCTYPE
        lib = ctypes.CDLL(_ida_lib_path(current_ea))
    elif current_os == 'linux':
        functype = ctypes.CFUNCTYPE
        lib = getattr(ctypes.cdll, 'lib' + ea_name)
    else:
        raise _os_error()
    return functype, lib 
Example #22
Source File: objcnew.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def __init__(self, func, restype=None, argtypes=None):
		if not callable(func):
			raise TypeError('%s is not callable' % func)
		if argtypes is None:
			argtypes = []
		InvokeFuncType = ctypes.CFUNCTYPE(restype, *argtypes)
		class block_literal(Structure):
			_fields_ = [('isa', c_void_p), ('flags', c_int), ('reserved', c_int), ('invoke', InvokeFuncType), ('descriptor', _block_descriptor)]
		block = block_literal()
		block.flags = (1<<28)
		block.invoke = InvokeFuncType(func)
		block.isa = ObjCClass('__NSGlobalBlock__').ptr
		self._as_parameter_ = block if LP64 else byref(block) 
Example #23
Source File: generate_special_function_declarations.py    From numba-scipy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def generate_signatures_file(signature_to_pointer):
    name_to_numba_signatures = collections.defaultdict(list)
    name_and_types_to_pointer = []
    for mangled_name, *signature in signature_to_pointer.keys():
        name = de_mangle_function_name(mangled_name)
        name_to_numba_signatures[name].append(
            '({},)'.format(', '.join(signature[1:]))
        )

        key = "('{}', {})".format(name, ', '.join(signature[1:]))
        address = (
            "get_cython_function_address('scipy.special.cython_special', '{}')"
            .format(mangled_name)
        )
        ctypes_signature = [NUMBA_TO_CTYPES[t] for t in signature]
        ctypes_cast = (
            'ctypes.CFUNCTYPE({})'.format(', '.join(ctypes_signature))
        )
        name_and_types_to_pointer.append(
            '{}: {}({})'.format(key, ctypes_cast, address)
        )

    name_to_numba_signatures = [
        "'{}': [{}]".format(name, ', '.join(signatures))
        for name, signatures in name_to_numba_signatures.items()
    ]
    name_to_numba_signatures = ',\n    '.join(name_to_numba_signatures)

    name_and_types_to_pointer = ',\n    '.join(name_and_types_to_pointer)
    content = SIGNATURES_TEMPLATE.format(
        NAME_TO_NUMBA_SIGNATURES=name_to_numba_signatures,
        NAME_AND_TYPES_TO_POINTER=name_and_types_to_pointer
    )
    with open(os.path.join(SPECIAL_DIR, 'signatures.py'), 'w') as f:
        f.write(content) 
Example #24
Source File: test_refcounts.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_callback(self):
        import sys

        proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
        def func(a, b):
            return a * b * 2
        f = proto(func)

        a = sys.getrefcount(ctypes.c_int)
        f(1, 2)
        self.assertEqual(sys.getrefcount(ctypes.c_int), a) 
Example #25
Source File: cpuid.py    From hase with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self) -> None:
        machine = platform.machine()  # type: ignore
        if machine not in ("AMD64", "x86_64", "x86", "i686"):
            raise SystemError("Only available for x86")

        opc = _POSIX_64_OPC if is_64bit else _CDECL_32_OPC

        size = len(opc)
        # bug in mypy:
        # https://github.com/python/mypy/pull/4869/commits/7e804feaac6be96bde5d27027192ba24155e495d#diff-b4c2ac9ec8ee99d26b77000717c1f572R93
        # cannot be detected correctly at the moment
        code = (ctypes.c_ubyte * size)(*opc)  # type: ignore

        self.libc = ctypes.cdll.LoadLibrary("libc.so.6")
        self.libc.valloc.restype = ctypes.c_void_p
        self.libc.valloc.argtypes = [ctypes.c_size_t]
        self.addr = self.libc.valloc(size)
        if not self.addr:
            raise MemoryError("Could not allocate memory")

        self.libc.mprotect.restype = c_int
        self.libc.mprotect.argtypes = [c_void_p, c_size_t, c_int]
        ret = self.libc.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, c_uint32)
        self.func_ptr = func_type(self.addr) 
Example #26
Source File: _espeak.py    From pyttsx3 with GNU General Public License v3.0 5 votes vote down vote up
def cfunc(name, dll, result, *args):
    '''build and apply a ctypes prototype complete with parameter flags'''
    atypes = []
    aflags = []
    for arg in args:
        atypes.append(arg[1])
        aflags.append((arg[2], arg[0]) + arg[3:])
    return CFUNCTYPE(result, *atypes)((name, dll), tuple(aflags)) 
Example #27
Source File: runtime.py    From blackmamba with MIT License 5 votes vote down vote up
def swizzle(cls_name, selector_name, fn):
    cls = ObjCClass(cls_name).ptr

    new_selector_name = SWIZZLED_SELECTOR_PREFIX + selector_name
    new_selector = sel(new_selector_name)

    if c.class_getInstanceMethod(cls, new_selector):
        error('Skipping swizzling, already responds to {} selector'.format(new_selector_name))
        return

    selector = sel(selector_name)
    method = c.class_getInstanceMethod(cls, selector)
    if not method:
        error('Failed to get {} instance method'.format(selector_name))
        return

    type_encoding = c.method_getTypeEncoding(method)
    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, new_selector, imp, type_encoding)

    if not did_add:
        error('Failed to add {} method'.format(new_selector_name))
        return

    new_method = c.class_getInstanceMethod(cls, new_selector)
    method_exchangeImplementations(method, new_method)


#
# https://clang.llvm.org/docs/Block-ABI-Apple.html
# 
Example #28
Source File: kvstore.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def _set_updater(self, updater):
        """Sets a push updater into the store.

        This function only changes the local store. When running on multiple machines one must
        use `set_optimizer`.

        Parameters
        ----------
        updater : function
            The updater function.

        Examples
        --------
        >>> def update(key, input, stored):
        ...     print "update on key: %d" % key
        ...     stored += input * 2
        >>> kv._set_updater(update)
        >>> kv.pull('3', out=a)
        >>> print a.asnumpy()
        [[ 4.  4.  4.]
        [ 4.  4.  4.]]
        >>> kv.push('3', mx.nd.ones(shape))
        update on key: 3
        >>> kv.pull('3', out=a)
        >>> print a.asnumpy()
        [[ 6.  6.  6.]
        [ 6.  6.  6.]]
        """
        self._updater = updater
        # set updater with int keys
        _updater_proto = ctypes.CFUNCTYPE(
            None, ctypes.c_int, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
        self._updater_func = _updater_proto(_updater_wrapper(updater))
        # set updater with str keys
        _str_updater_proto = ctypes.CFUNCTYPE(
            None, ctypes.c_char_p, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
        self._str_updater_func = _str_updater_proto(_updater_wrapper(updater))
        check_call(_LIB.MXKVStoreSetUpdaterEx(self.handle, self._updater_func,
                                              self._str_updater_func, None)) 
Example #29
Source File: kvstore_server.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def run(self):
        """Run the server, whose behavior is like.


        >>> while receive(x):
        ...     if is_command x: controller(x)
        ...     else if is_key_value x: updater(x)
        """
        _ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
        check_call(_LIB.MXKVStoreRunServer(self.handle, _ctrl_proto(self._controller()), None)) 
Example #30
Source File: test_refcounts.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_callback(self):
        import sys

        proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
        def func(a, b):
            return a * b * 2
        f = proto(func)

        a = sys.getrefcount(ctypes.c_int)
        f(1, 2)
        self.assertEqual(sys.getrefcount(ctypes.c_int), a)