Python ctypes.ArgumentError() Examples

The following are 30 code examples of ctypes.ArgumentError(). 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: espeak.py    From pyttsx3 with GNU General Public License v3.0 6 votes vote down vote up
def setProperty(self, name, value):
        if name == 'voice':
            if value is None:
                return
            try:
                utf8Value = toUtf8(value)
                _espeak.SetVoiceByName(utf8Value)
            except ctypes.ArgumentError as e:
                raise ValueError(str(e))
        elif name == 'rate':
            try:
                _espeak.SetParameter(_espeak.RATE, value, 0)
            except ctypes.ArgumentError as e:
                raise ValueError(str(e))
        elif name == 'volume':
            try:
                _espeak.SetParameter(
                    _espeak.VOLUME, int(round(value * 100, 2)), 0)
            except TypeError as e:
                raise ValueError(str(e))
        else:
            raise KeyError('unknown property %s' % name) 
Example #2
Source File: util.py    From dm_control with Apache License 2.0 6 votes vote down vote up
def cast_func_to_c_void_p(func, cfunctype):
  """Casts a native function pointer or a Python callable into `c_void_p`.

  Args:
    func: A callable, or a `c_void_p` pointing to a native function, or `None`.
    cfunctype: A `CFUNCTYPE` prototype that is used to wrap `func` if it is
      a Python callable.

  Returns:
    A tuple `(func_ptr, wrapped_pyfunc)`, where `func_ptr` is a `c_void_p`
    object, and `wrapped_pyfunc` is a `CFUNCTYPE` object that wraps `func` if
    it is a Python callable. (If `func` is not a Python callable then
    `wrapped_pyfunc` is `None`.)
  """
  if not (callable(func) or isinstance(func, ctypes.c_void_p) or func is None):
    raise TypeError(_INVALID_CALLBACK_TYPE.format(func))
  try:
    new_func_ptr = ctypes.cast(func, ctypes.c_void_p)
    wrapped_pyfunc = None
  except ctypes.ArgumentError:
    wrapped_pyfunc = cfunctype(func)
    new_func_ptr = ctypes.cast(wrapped_pyfunc, ctypes.c_void_p)
  return new_func_ptr, wrapped_pyfunc 
Example #3
Source File: win32_output.py    From android_universal with MIT License 6 votes vote down vote up
def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8')) 
Example #4
Source File: win32_output.py    From android_universal with MIT License 6 votes vote down vote up
def _coord_byval(coord):
    """
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When runing ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    """
    return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)


#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.) 
Example #5
Source File: test_unicode.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_wcslen(self):
        dll = ctypes.CDLL(_ctypes_test.__file__)
        wcslen = dll.my_wcslen
        wcslen.argtypes = [ctypes.c_wchar_p]

        self.assertEqual(wcslen("abc"), 3)
        self.assertEqual(wcslen("ab\u2070"), 3)
        self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4") 
Example #6
Source File: test_parameters.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_noctypes_argtype(self):
        import _ctypes_test
        from ctypes import CDLL, c_void_p, ArgumentError

        func = CDLL(_ctypes_test.__file__)._testfunc_p_p
        func.restype = c_void_p
        # TypeError: has no from_param method
        self.assertRaises(TypeError, setattr, func, "argtypes", (object,))

        class Adapter(object):
            def from_param(cls, obj):
                return None

        func.argtypes = (Adapter(),)
        self.assertEqual(func(None), None)
        self.assertEqual(func(object()), None)

        class Adapter(object):
            def from_param(cls, obj):
                return obj

        func.argtypes = (Adapter(),)
        # don't know how to convert parameter 1
        self.assertRaises(ArgumentError, func, object())
        self.assertEqual(func(c_void_p(42)), 42)

        class Adapter(object):
            def from_param(cls, obj):
                raise ValueError(obj)

        func.argtypes = (Adapter(),)
        # ArgumentError: argument 1: ValueError: 99
        self.assertRaises(ArgumentError, func, 99)


################################################################ 
Example #7
Source File: test_parameters.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_noctypes_argtype(self):
        import _ctypes_test
        from ctypes import CDLL, c_void_p, ArgumentError

        func = CDLL(_ctypes_test.__file__)._testfunc_p_p
        func.restype = c_void_p
        # TypeError: has no from_param method
        self.assertRaises(TypeError, setattr, func, "argtypes", (object,))

        class Adapter(object):
            def from_param(cls, obj):
                return None

        func.argtypes = (Adapter(),)
        self.assertEqual(func(None), None)
        self.assertEqual(func(object()), None)

        class Adapter(object):
            def from_param(cls, obj):
                return obj

        func.argtypes = (Adapter(),)
        # don't know how to convert parameter 1
        self.assertRaises(ArgumentError, func, object())
        self.assertEqual(func(c_void_p(42)), 42)

        class Adapter(object):
            def from_param(cls, obj):
                raise ValueError(obj)

        func.argtypes = (Adapter(),)
        # ArgumentError: argument 1: ValueError: 99
        self.assertRaises(ArgumentError, func, 99) 
Example #8
Source File: syswow64.py    From PythonForWindows with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def try_generate_stub_target(shellcode, argument_buffer, target, errcheck=None):
    if not windows.current_process.is_wow_64:
        raise ValueError("Calling execute_64bits_code_from_syswow from non-syswow process")
    native_caller = generate_64bits_execution_stub_from_syswow(shellcode)
    native_caller.errcheck = errcheck if errcheck is not None else target.errcheck
    # Generate the wrapper function that fill the argument_buffer
    expected_arguments_number = len(target.prototype._argtypes_)
    def wrapper(*args):
        if len(args) != expected_arguments_number:
            raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args)))
        # Transform args (ctypes byref possibly) to int
        writable_args = []
        for i, value in enumerate(args):
            if not isinstance(value, int_types):
                try:
                    value = ctypes.cast(value, ctypes.c_void_p).value
                except ctypes.ArgumentError as e:
                    raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__))
            writable_args.append(value)
        # Build buffer
        buffer = struct.pack("<" + "Q" * len(writable_args), *writable_args)
        ctypes.memmove(argument_buffer, buffer, len(buffer))
        # Copy origincal args in function, for errcheck if needed
        native_caller.current_original_args = args # TODO: THIS IS NOT THREAD SAFE
        return native_caller()
    wrapper.__name__ = "{0}<syswow64>".format(target.__name__,)
    wrapper.__doc__ = "This is a wrapper to {0} in 64b mode, it accept <{1}> args".format(target.__name__, expected_arguments_number)
    return wrapper 
Example #9
Source File: test_geos.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_buffer(self):
        bg = self.geometries.buffer_geoms[0]
        g = fromstr(bg.wkt)

        # Can't use a floating-point for the number of quadsegs.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer(bg.width, quadsegs=1.1)

        self._test_buffer(self.geometries.buffer_geoms, 'buffer') 
Example #10
Source File: test_geos.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_buffer_with_style(self):
        bg = self.geometries.buffer_with_style_geoms[0]
        g = fromstr(bg.wkt)

        # Can't use a floating-point for the number of quadsegs.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer_with_style(bg.width, quadsegs=1.1)

        # Can't use a floating-point for the end cap style.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer_with_style(bg.width, end_cap_style=1.2)
        # Can't use a end cap style that is not in the enum.
        with self.assertRaises(GEOSException):
            g.buffer_with_style(bg.width, end_cap_style=55)

        # Can't use a floating-point for the join style.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer_with_style(bg.width, join_style=1.3)
        # Can't use a join style that is not in the enum.
        with self.assertRaises(GEOSException):
            g.buffer_with_style(bg.width, join_style=66)

        self._test_buffer(
            itertools.chain(self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms),
            'buffer_with_style',
        ) 
Example #11
Source File: test_geos.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_buffer(self):
        bg = self.geometries.buffer_geoms[0]
        g = fromstr(bg.wkt)

        # Can't use a floating-point for the number of quadsegs.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer(bg.width, quadsegs=1.1)

        self._test_buffer(self.geometries.buffer_geoms, 'buffer') 
Example #12
Source File: test_geos.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_buffer_with_style(self):
        bg = self.geometries.buffer_with_style_geoms[0]
        g = fromstr(bg.wkt)

        # Can't use a floating-point for the number of quadsegs.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer_with_style(bg.width, quadsegs=1.1)

        # Can't use a floating-point for the end cap style.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer_with_style(bg.width, end_cap_style=1.2)
        # Can't use a end cap style that is not in the enum.
        with self.assertRaises(GEOSException):
            g.buffer_with_style(bg.width, end_cap_style=55)

        # Can't use a floating-point for the join style.
        with self.assertRaises(ctypes.ArgumentError):
            g.buffer_with_style(bg.width, join_style=1.3)
        # Can't use a join style that is not in the enum.
        with self.assertRaises(GEOSException):
            g.buffer_with_style(bg.width, join_style=66)

        self._test_buffer(
            itertools.chain(self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms),
            'buffer_with_style',
        ) 
Example #13
Source File: test_ctypeslib.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_arguments(self):
        """ Test that arguments are coerced from arrays """
        c_forward_pointer.restype = ctypes.c_void_p
        c_forward_pointer.argtypes = (ndpointer(ndim=2),)

        c_forward_pointer(np.zeros((2, 3)))
        # too many dimensions
        assert_raises(
            ctypes.ArgumentError, c_forward_pointer, np.zeros((2, 3, 4))) 
Example #14
Source File: test_unicode.py    From android_universal with MIT License 5 votes vote down vote up
def test_wcslen(self):
        dll = ctypes.CDLL(_ctypes_test.__file__)
        wcslen = dll.my_wcslen
        wcslen.argtypes = [ctypes.c_wchar_p]

        self.assertEqual(wcslen("abc"), 3)
        self.assertEqual(wcslen("ab\u2070"), 3)
        self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4") 
Example #15
Source File: test_parameters.py    From android_universal with MIT License 5 votes vote down vote up
def test_noctypes_argtype(self):
        import _ctypes_test
        from ctypes import CDLL, c_void_p, ArgumentError

        func = CDLL(_ctypes_test.__file__)._testfunc_p_p
        func.restype = c_void_p
        # TypeError: has no from_param method
        self.assertRaises(TypeError, setattr, func, "argtypes", (object,))

        class Adapter(object):
            def from_param(cls, obj):
                return None

        func.argtypes = (Adapter(),)
        self.assertEqual(func(None), None)
        self.assertEqual(func(object()), None)

        class Adapter(object):
            def from_param(cls, obj):
                return obj

        func.argtypes = (Adapter(),)
        # don't know how to convert parameter 1
        self.assertRaises(ArgumentError, func, object())
        self.assertEqual(func(c_void_p(42)), 42)

        class Adapter(object):
            def from_param(cls, obj):
                raise ValueError(obj)

        func.argtypes = (Adapter(),)
        # ArgumentError: argument 1: ValueError: 99
        self.assertRaises(ArgumentError, func, 99) 
Example #16
Source File: testsuite.py    From ctypesgen with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_sqrt(self):
        """Based on math_functions.py"""
        module = self.module

        self.assertEqual(module.sqrt(4), 2)

        def local_test():
            module.sin("foobar")

        self.assertRaises(ctypes.ArgumentError, local_test) 
Example #17
Source File: testsuite.py    From ctypesgen with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_bad_args_string_not_number(self):
        """Based on math_functions.py"""
        module = self.module

        def local_test():
            module.sin("foobar")

        self.assertRaises(ctypes.ArgumentError, local_test) 
Example #18
Source File: test_pyglet_renderer.py    From flow with MIT License 5 votes vote down vote up
def test_close(self):
        # Initialize a pyglet renderer
        self.renderer = Renderer(
            self.network,
            mode=self.mode,
            save_render=self.save_render,
            sight_radius=self.sight_radius,
            pxpm=self.pxpm,
            show_radius=self.show_radius,
            alpha=self.alpha
        )

        self.renderer.close()

        _human_orientations, _machine_orientations, \
            _human_dynamics, _machine_dynamics, \
            _human_logs, _machine_logs = self.data[1]
        self.assertRaises(
            ctypes.ArgumentError,
            self.renderer.render,
            _human_orientations,
            _machine_orientations,
            _human_dynamics,
            _machine_dynamics,
            _human_logs,
            _machine_logs
        ) 
Example #19
Source File: memory.py    From zugbruecke with GNU Lesser General Public License v2.1 5 votes vote down vote up
def is_null_pointer(ctypes_pointer):

	try:
		return ctypes.cast(ctypes_pointer, ctypes.c_void_p).value is None
	except ctypes.ArgumentError: # catch non-pointer arguments
		return False 
Example #20
Source File: test_error_callargs.py    From zugbruecke with GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_error_callargs_unconfigured_right_number_of_args_nondefault_float():

	dll = ctypes.windll.LoadLibrary('tests/demo_dll.dll')
	add_floats = dll.add_floats

	with pytest.raises(ctypes.ArgumentError):
		a = add_floats(1.2, 3.6) 
Example #21
Source File: test_binding.py    From llvmlite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_close(self):
        mod = self.module()
        str(mod)
        mod.close()
        with self.assertRaises(ctypes.ArgumentError):
            str(mod)
        mod.close() 
Example #22
Source File: test_binding.py    From llvmlite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_with(self):
        mod = self.module()
        str(mod)
        with mod:
            str(mod)
        with self.assertRaises(ctypes.ArgumentError):
            str(mod)
        with self.assertRaises(RuntimeError):
            with mod:
                pass 
Example #23
Source File: test_binding.py    From llvmlite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_link_in(self):
        dest = self.module()
        src = self.module(asm_mul)
        dest.link_in(src)
        self.assertEqual(
            sorted(f.name for f in dest.functions), ["mul", "sum"])
        dest.get_function("mul")
        dest.close()
        with self.assertRaises(ctypes.ArgumentError):
            src.get_function("mul") 
Example #24
Source File: test_binding.py    From llvmlite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_close(self):
        ee = self.jit(self.module())
        ee.close()
        ee.close()
        with self.assertRaises(ctypes.ArgumentError):
            ee.finalize_object() 
Example #25
Source File: test_binding.py    From llvmlite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_with(self):
        ee = self.jit(self.module())
        with ee:
            pass
        with self.assertRaises(RuntimeError):
            with ee:
                pass
        with self.assertRaises(ctypes.ArgumentError):
            ee.finalize_object() 
Example #26
Source File: test_unicode.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_wcslen(self):
        dll = ctypes.CDLL(_ctypes_test.__file__)
        wcslen = dll.my_wcslen
        wcslen.argtypes = [ctypes.c_wchar_p]

        self.assertEqual(wcslen("abc"), 3)
        self.assertEqual(wcslen("ab\u2070"), 3)
        self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4") 
Example #27
Source File: test_unicode.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_ascii_strict(self):
        wcslen = self.wcslen
        ctypes.set_conversion_mode("ascii", "strict")
        # no conversions take place with unicode arguments
        self.assertEqual(wcslen(u"abc"), 3)
        self.assertEqual(wcslen(u"ab\u2070"), 3)
        # string args are converted
        self.assertEqual(wcslen("abc"), 3)
        self.assertRaises(ctypes.ArgumentError, wcslen, "ab�") 
Example #28
Source File: test_unicode.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_ascii_strict(self):
        func = self.func
        ctypes.set_conversion_mode("ascii", "strict")
        self.assertEqual(func("abc"), "abc")
        self.assertEqual(func(u"abc"), "abc")
        self.assertRaises(ctypes.ArgumentError, func, u"ab�") 
Example #29
Source File: test_parameters.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_noctypes_argtype(self):
        import _ctypes_test
        from ctypes import CDLL, c_void_p, ArgumentError

        func = CDLL(_ctypes_test.__file__)._testfunc_p_p
        func.restype = c_void_p
        # TypeError: has no from_param method
        self.assertRaises(TypeError, setattr, func, "argtypes", (object,))

        class Adapter(object):
            def from_param(cls, obj):
                return None

        func.argtypes = (Adapter(),)
        self.assertEqual(func(None), None)
        self.assertEqual(func(object()), None)

        class Adapter(object):
            def from_param(cls, obj):
                return obj

        func.argtypes = (Adapter(),)
        # don't know how to convert parameter 1
        self.assertRaises(ArgumentError, func, object())
        self.assertEqual(func(c_void_p(42)), 42)

        class Adapter(object):
            def from_param(cls, obj):
                raise ValueError(obj)

        func.argtypes = (Adapter(),)
        # ArgumentError: argument 1: ValueError: 99
        self.assertRaises(ArgumentError, func, 99) 
Example #30
Source File: test_unicode.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_ascii_strict(self):
            ctypes.set_conversion_mode("ascii", "strict")
            # no conversions take place with unicode arguments
            self.assertEqual(wcslen(u"abc"), 3)
            self.assertEqual(wcslen(u"ab\u2070"), 3)
            # string args are converted
            self.assertEqual(wcslen("abc"), 3)
            self.assertRaises(ctypes.ArgumentError, wcslen, "ab�")