Python cffi.FFI Examples
The following are 30
code examples of cffi.FFI().
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
cffi
, or try the search function
.
Example #1
Source File: test_function.py From SwiftKitten with MIT License | 6 votes |
def test_callback_returning_void(self): ffi = FFI(backend=self.Backend()) for returnvalue in [None, 42]: def cb(): return returnvalue fptr = ffi.callback("void(*)(void)", cb) old_stderr = sys.stderr try: sys.stderr = StringIO() returned = fptr() printed = sys.stderr.getvalue() finally: sys.stderr = old_stderr assert returned is None if returnvalue is None: assert printed == '' else: assert "None" in printed
Example #2
Source File: test_ownlib.py From SwiftKitten with MIT License | 6 votes |
def test_keepalive_lib(self): if self.module is None: py.test.skip("fix the auto-generation of the tiny test lib") ffi = FFI(backend=self.Backend()) ffi.cdef(""" int test_getting_errno(void); """) ownlib = ffi.dlopen(self.module) ffi_r = weakref.ref(ffi) ownlib_r = weakref.ref(ownlib) func = ownlib.test_getting_errno del ffi import gc; gc.collect() # ownlib stays alive assert ownlib_r() is not None assert ffi_r() is not None # kept alive by ownlib res = func() assert res == -1
Example #3
Source File: test_parsing.py From SwiftKitten with MIT License | 6 votes |
def test_remove_comments(): ffi = FFI(backend=FakeBackend()) ffi.cdef(""" double /*comment here*/ sin // blah blah /* multi- line- //comment */ ( // foo double // bar /* <- ignored, because it's in a comment itself x, double/*several*//*comment*/y) /*on the same line*/ ; """) m = ffi.dlopen(lib_m) func = m.sin assert func.name == 'sin' assert func.BType == '<func (<double>, <double>), <double>, False>'
Example #4
Source File: test_parsing.py From SwiftKitten with MIT License | 6 votes |
def test_remove_line_continuation_comments(): ffi = FFI(backend=FakeBackend()) ffi.cdef(""" double // blah \\ more comments x(void); double // blah\\\\ y(void); double // blah\\ \ etc z(void); """) m = ffi.dlopen(lib_m) m.x m.y m.z
Example #5
Source File: test_ownlib.py From SwiftKitten with MIT License | 6 votes |
def test_my_array_no_length(self): if self.module is None: py.test.skip("fix the auto-generation of the tiny test lib") if self.Backend is CTypesBackend: py.test.skip("not supported by the ctypes backend") ffi = FFI(backend=self.Backend()) ffi.cdef(""" int my_array[]; """) ownlib = ffi.dlopen(self.module) for i in range(7): assert ownlib.my_array[i] == i py.test.raises(TypeError, len, ownlib.my_array) ownlib.my_array = list(range(10, 17)) for i in range(7): assert ownlib.my_array[i] == 10 + i ownlib.my_array = list(range(7)) for i in range(7): assert ownlib.my_array[i] == i
Example #6
Source File: test_ownlib.py From SwiftKitten with MIT License | 6 votes |
def test_my_array_7(self): if self.module is None: py.test.skip("fix the auto-generation of the tiny test lib") ffi = FFI(backend=self.Backend()) ffi.cdef(""" int my_array[7]; """) ownlib = ffi.dlopen(self.module) for i in range(7): assert ownlib.my_array[i] == i assert len(ownlib.my_array) == 7 if self.Backend is CTypesBackend: py.test.skip("not supported by the ctypes backend") ownlib.my_array = list(range(10, 17)) for i in range(7): assert ownlib.my_array[i] == 10 + i ownlib.my_array = list(range(7)) for i in range(7): assert ownlib.my_array[i] == i
Example #7
Source File: test_ownlib.py From SwiftKitten with MIT License | 6 votes |
def test_setting_errno(self): if self.module is None: py.test.skip("fix the auto-generation of the tiny test lib") if sys.platform == 'win32': py.test.skip("fails, errno at multiple addresses") if self.Backend is CTypesBackend and '__pypy__' in sys.modules: py.test.skip("XXX errno issue with ctypes on pypy?") ffi = FFI(backend=self.Backend()) ffi.cdef(""" int test_setting_errno(void); """) ownlib = ffi.dlopen(self.module) ffi.errno = 42 res = ownlib.test_setting_errno() assert res == 42 assert ffi.errno == 42
Example #8
Source File: test_ffi_backend.py From SwiftKitten with MIT License | 6 votes |
def test_ffi_new_allocator_4(self): ffi = FFI(backend=self.Backend()) py.test.raises(TypeError, ffi.new_allocator, free=lambda x: None) # def myalloc2(size): raise LookupError alloc2 = ffi.new_allocator(myalloc2) py.test.raises(LookupError, alloc2, "int[5]") # def myalloc3(size): return 42 alloc3 = ffi.new_allocator(myalloc3) e = py.test.raises(TypeError, alloc3, "int[5]") assert str(e.value) == "alloc() must return a cdata object (got int)" # def myalloc4(size): return ffi.cast("int", 42) alloc4 = ffi.new_allocator(myalloc4) e = py.test.raises(TypeError, alloc4, "int[5]") assert str(e.value) == "alloc() must return a cdata pointer, not 'int'" # def myalloc5(size): return ffi.NULL alloc5 = ffi.new_allocator(myalloc5) py.test.raises(MemoryError, alloc5, "int[5]")
Example #9
Source File: test_ffi_backend.py From SwiftKitten with MIT License | 6 votes |
def test_callback_onerror(self): ffi = FFI(backend=self.Backend()) seen = [] def oops(*args): seen.append(args) def otherfunc(): raise LookupError def cb(n): otherfunc() a = ffi.callback("int(*)(int)", cb, error=42, onerror=oops) res = a(234) assert res == 42 assert len(seen) == 1 exc, val, tb = seen[0] assert exc is LookupError assert isinstance(val, LookupError) assert tb.tb_frame.f_code.co_name == 'cb' assert tb.tb_frame.f_locals['n'] == 234
Example #10
Source File: test_function.py From SwiftKitten with MIT License | 6 votes |
def test_free_callback_cycle(self): if self.Backend is CTypesBackend: py.test.skip("seems to fail with the ctypes backend on windows") import weakref def make_callback(data): container = [data] callback = ffi.callback('int()', lambda: len(container)) container.append(callback) # Ref cycle: callback -> lambda (closure) -> container -> callback return callback class Data(object): pass ffi = FFI(backend=self.Backend()) data = Data() callback = make_callback(data) wr = weakref.ref(data) del callback, data for i in range(3): if wr() is not None: import gc; gc.collect() assert wr() is None # 'data' does not leak
Example #11
Source File: test_parsing.py From SwiftKitten with MIT License | 6 votes |
def test__is_constant_globalvar(): for input, expected_output in [ ("int a;", False), ("const int a;", True), ("int *a;", False), ("const int *a;", False), ("int const *a;", False), ("int *const a;", True), ("int a[5];", False), ("const int a[5];", False), ("int *a[5];", False), ("const int *a[5];", False), ("int const *a[5];", False), ("int *const a[5];", False), ("int a[5][6];", False), ("const int a[5][6];", False), ]: ffi = FFI() ffi.cdef(input) declarations = ffi._parser._declarations assert ('constant a' in declarations) == expected_output assert ('variable a' in declarations) == (not expected_output)
Example #12
Source File: test_function.py From SwiftKitten with MIT License | 6 votes |
def test_fputs_custom_FILE(self): if self.Backend is CTypesBackend: py.test.skip("FILE not supported with the ctypes backend") filename = str(udir.join('fputs_custom_FILE')) ffi = FFI(backend=self.Backend()) ffi.cdef("int fputs(const char *, FILE *);") C = ffi.dlopen(None) with open(filename, 'wb') as f: f.write(b'[') C.fputs(b"hello from custom file", f) f.write(b'][') C.fputs(b"some more output", f) f.write(b']') with open(filename, 'rb') as f: res = f.read() assert res == b'[hello from custom file][some more output]'
Example #13
Source File: ctc.py From ngraph-python with Apache License 2.0 | 6 votes |
def __init__(self, on_device='cpu', blank_label=0): libpath = get_ctc_lib() self.ffi = FFI() self.ffi.cdef(ctc_header()) self.ctclib = self.ffi.dlopen(libpath) supported_devices = ['cpu', 'gpu'] if on_device not in supported_devices: print("the requested device {} is not supported".format( on_device), file=sys.stderr) sys.exit(1) assign_device = 0 if on_device is 'cpu' else 1 self.options = self.ffi.new('ctcOptions*', {"loc": assign_device, "blank_label": blank_label})[0] self.size_in_bytes = self.ffi.new("size_t*") self.nout = None self.bsz = None
Example #14
Source File: interop.py From vnpy_crypto with MIT License | 6 votes |
def cast_int_addr(n): """Cast an address to a Python int This could be a Python integer or a CFFI pointer """ if isinstance(n, (int, long)): return n try: import cffi except ImportError: pass else: # from pyzmq, this is an FFI void * ffi = cffi.FFI() if isinstance(n, ffi.CData): return int(ffi.cast("size_t", n)) raise ValueError("Cannot cast %r to int" % n)
Example #15
Source File: test_parsing.py From SwiftKitten with MIT License | 5 votes |
def test_unknown_argument_type(): ffi = FFI() e = py.test.raises(CDefError, ffi.cdef, "void f(foobarbazzz);") assert str(e.value) == ("f arg 1: unknown type 'foobarbazzz' (if you meant" " to use the old C syntax of giving untyped" " arguments, it is not supported)")
Example #16
Source File: test_ownlib.py From SwiftKitten with MIT License | 5 votes |
def test_getting_errno(self): if self.module is None: py.test.skip("fix the auto-generation of the tiny test lib") if sys.platform == 'win32': py.test.skip("fails, errno at multiple addresses") ffi = FFI(backend=self.Backend()) ffi.cdef(""" int test_getting_errno(void); """) ownlib = ffi.dlopen(self.module) res = ownlib.test_getting_errno() assert res == -1 assert ffi.errno == 123
Example #17
Source File: test_parsing.py From SwiftKitten with MIT License | 5 votes |
def test_bool(): ffi = FFI() ffi.cdef("void f(bool);") # ffi = FFI() ffi.cdef("typedef _Bool bool; void f(bool);")
Example #18
Source File: test_parsing.py From SwiftKitten with MIT License | 5 votes |
def test_redefine_common_type(): prefix = "" if sys.version_info < (3,) else "b" ffi = FFI() ffi.cdef("typedef char FILE;") assert repr(ffi.cast("FILE", 123)) == "<cdata 'char' %s'{'>" % prefix ffi.cdef("typedef char int32_t;") assert repr(ffi.cast("int32_t", 123)) == "<cdata 'char' %s'{'>" % prefix ffi = FFI() ffi.cdef("typedef int bool, *FILE;") assert repr(ffi.cast("bool", 123)) == "<cdata 'int' 123>" assert re.match(r"<cdata 'int [*]' 0[xX]?0*7[bB]>", repr(ffi.cast("FILE", 123))) ffi = FFI() ffi.cdef("typedef bool (*fn_t)(bool, bool);") # "bool," but within "( )"
Example #19
Source File: test_parsing.py From SwiftKitten with MIT License | 5 votes |
def test_simple(): ffi = FFI(backend=FakeBackend()) ffi.cdef("double sin(double x);") m = ffi.dlopen(lib_m) func = m.sin # should be a callable on real backends assert func.name == 'sin' assert func.BType == '<func (<double>), <double>, False>'
Example #20
Source File: callback_in_thread.py From SwiftKitten with MIT License | 5 votes |
def _run_callback_in_thread(): ffi = FFI() ffi.cdef(""" typedef int (*mycallback_func_t)(int, int); int threaded_ballback_test(mycallback_func_t mycb); """) lib = ffi.verify(""" #include <pthread.h> typedef int (*mycallback_func_t)(int, int); void *my_wait_function(void *ptr) { mycallback_func_t cbfunc = (mycallback_func_t)ptr; cbfunc(10, 10); cbfunc(12, 15); return NULL; } int threaded_ballback_test(mycallback_func_t mycb) { pthread_t thread; pthread_create(&thread, NULL, my_wait_function, (void*)mycb); return 0; } """, extra_compile_args=['-pthread']) seen = [] @ffi.callback('int(*)(int,int)') def mycallback(x, y): time.sleep(0.022) seen.append((x, y)) return 0 lib.threaded_ballback_test(mycallback) count = 300 while len(seen) != 2: time.sleep(0.01) count -= 1 assert count > 0, "timeout" assert seen == [(10, 10), (12, 15)]
Example #21
Source File: test_parsing.py From SwiftKitten with MIT License | 5 votes |
def test_void_renamed_as_only_arg(): ffi = FFI() ffi.cdef("typedef void void_t1;" "typedef void_t1 void_t;" "typedef int (*func_t)(void_t);") assert ffi.typeof("func_t").args == ()
Example #22
Source File: test_parsing.py From SwiftKitten with MIT License | 5 votes |
def test_unknown_name(): ffi = FFI() e = py.test.raises(CDefError, ffi.cast, "foobarbazunknown", 0) assert str(e.value) == "unknown identifier 'foobarbazunknown'" e = py.test.raises(CDefError, ffi.cast, "foobarbazunknown*", 0) assert str(e.value).startswith('cannot parse "foobarbazunknown*"') e = py.test.raises(CDefError, ffi.cast, "int(*)(foobarbazunknown)", 0) assert str(e.value).startswith('cannot parse "int(*)(foobarbazunknown)"')
Example #23
Source File: test_ownlib.py From SwiftKitten with MIT License | 5 votes |
def test_struct_by_value(self): if self.module is None: py.test.skip("fix the auto-generation of the tiny test lib") ffi = FFI(backend=self.Backend()) ffi.cdef(""" typedef struct { long x; long y; } POINT; typedef struct { long left; long top; long right; long bottom; } RECT; long left, top, right, bottom; RECT ReturnRect(int i, RECT ar, RECT* br, POINT cp, RECT dr, RECT *er, POINT fp, RECT gr); """) ownlib = ffi.dlopen(self.module) rect = ffi.new('RECT[1]') pt = ffi.new('POINT[1]') pt[0].x = 15 pt[0].y = 25 rect[0].left = ownlib.left rect[0].right = ownlib.right rect[0].top = ownlib.top rect[0].bottom = ownlib.bottom for i in range(4): ret = ownlib.ReturnRect(i, rect[0], rect, pt[0], rect[0], rect, pt[0], rect[0]) assert ret.left == ownlib.left assert ret.right == ownlib.right assert ret.top == ownlib.top assert ret.bottom == ownlib.bottom
Example #24
Source File: test_parsing.py From SwiftKitten with MIT License | 5 votes |
def test_typedef_array_convert_array_to_pointer(): ffi = FFI(backend=FakeBackend()) ffi.cdef(""" typedef int (*fn_t)(int[5]); """) with ffi._lock: type = ffi._parser.parse_type("fn_t") BType = ffi._get_cached_btype(type) assert str(BType) == '<func (<pointer to <int>>), <int>, False>'
Example #25
Source File: test_function.py From SwiftKitten with MIT License | 5 votes |
def test_stdcall_only_on_windows(self): ffi = FFI(backend=self.Backend()) ffi.cdef("double __stdcall sin(double x);") # stdcall ignored m = ffi.dlopen(lib_m) if (sys.platform == 'win32' and sys.maxsize < 2**32 and self.Backend is not CTypesBackend): assert "double(__stdcall *)(double)" in str(ffi.typeof(m.sin)) else: assert "double(*)(double)" in str(ffi.typeof(m.sin)) x = m.sin(1.23) assert x == math.sin(1.23)
Example #26
Source File: test_function.py From SwiftKitten with MIT License | 5 votes |
def test_windows_stdcall(self): if sys.platform != 'win32': py.test.skip("Windows-only test") if self.Backend is CTypesBackend: py.test.skip("not with the ctypes backend") ffi = FFI(backend=self.Backend()) ffi.cdef(""" BOOL QueryPerformanceFrequency(LONGLONG *lpFrequency); """) m = ffi.dlopen("Kernel32.dll") p_freq = ffi.new("LONGLONG *") res = m.QueryPerformanceFrequency(p_freq) assert res != 0 assert p_freq[0] != 0
Example #27
Source File: test_function.py From SwiftKitten with MIT License | 5 votes |
def test_wraps_from_stdlib(self): import functools ffi = FFI(backend=self.Backend()) ffi.cdef(""" double sin(double x); """) def my_decorator(f): @functools.wraps(f) def wrapper(*args): return f(*args) + 100 return wrapper m = ffi.dlopen(lib_m) sin100 = my_decorator(m.sin) x = sin100(1.23) assert x == math.sin(1.23) + 100
Example #28
Source File: test_function.py From SwiftKitten with MIT License | 5 votes |
def test_unsigned_char_star_accepts_string(self): if self.Backend is CTypesBackend: py.test.skip("not supported by the ctypes backend") ffi = FFI(backend=self.Backend()) ffi.cdef("""int strlen(unsigned char *);""") lib = ffi.dlopen(None) res = lib.strlen(b"hello") assert res == 5
Example #29
Source File: test_function.py From SwiftKitten with MIT License | 5 votes |
def test_signed_char_star_accepts_string(self): if self.Backend is CTypesBackend: py.test.skip("not supported by the ctypes backend") ffi = FFI(backend=self.Backend()) ffi.cdef("""int strlen(signed char *);""") lib = ffi.dlopen(None) res = lib.strlen(b"hello") assert res == 5
Example #30
Source File: test_function.py From SwiftKitten with MIT License | 5 votes |
def test_void_star_accepts_string(self): ffi = FFI(backend=self.Backend()) ffi.cdef("""int strlen(const void *);""") lib = ffi.dlopen(None) res = lib.strlen(b"hello") assert res == 5