def language_builder(package, function, dir): runtime_root = _runtime_root() runtime_gyp = _gyp_target(runtime_root / 'project.gyp', 'runtime') language_root = Path(dir).resolve() language_gyp = _gyp_target(language_root / 'binding.gyp', function + '_binding') sources = [ str(language_root / f) for f in language_gyp['sources'] if f != 'src/binding.cc' ] include_dirs = [str(runtime_root / d) for d in runtime_gyp['include_dirs']] include_dirs.extend( [str(language_root / d) for d in language_gyp['include_dirs']]) compile_args = language_gyp.get('cflags_c', []) builder = FFI() builder.include(runtime_builder()) builder.cdef('const TSLanguage *{}(void);'.format(function)) builder.set_source(package, ''' #include <tree_sitter/runtime.h> #include <tree_sitter/parser.h> const TSLanguage *{}(void); '''.format(function), sources=sources, include_dirs=include_dirs, extra_compile_args=compile_args) return builder
def test_introspect_included_type(self): ffi1 = FFI() ffi2 = FFI() ffi1.cdef("typedef signed char schar_t; struct sint_t { int x; };") ffi2.include(ffi1) assert ffi1.list_types() == ffi2.list_types() == ( ['schar_t'], ['sint_t'], [])
def test_introspect_included_type(self): ffi1 = FFI() ffi2 = FFI() ffi1.cdef("typedef signed char schar_t; struct sint_t { int x; };") ffi2.include(ffi1) assert ffi1.list_types() == ffi2.list_types() == (['schar_t' ], ['sint_t'], [])
def load(self): ffi = FFI() ffi.include(self.ffi) ffi.cdef('\n'.join(self.cdef)) lib = ffi.dlopen(None) for n, cb in self.callbacks.items(): setattr(lib, '_' + n, cb) self.lib = lib
def test_no_cross_include(): baseffi = FFI() baseffi.set_source('test_no_cross_include_base', "..source..") # ffi = FFI() ffi.include(baseffi) target = udir.join('test_no_cross_include.py') py.test.raises(VerificationError, make_py_source, ffi, 'test_no_cross_include', str(target))
def test_include_1(): ffi1 = FFI() ffi1.cdef("typedef double foo_t;") verify(ffi1, "test_include_1_parent", "typedef double foo_t;") ffi = FFI() ffi.include(ffi1) ffi.cdef("foo_t ff1(foo_t);") lib = verify(ffi, "test_include_1", "double ff1(double x) { return 42.5; }") assert lib.ff1(0) == 42.5 assert ffi1.typeof("foo_t") is ffi.typeof("foo_t") is ffi.typeof("double")
def check_type_table(input, expected_output, included=None): ffi = FFI() if included: ffi1 = FFI() ffi1.cdef(included) ffi.include(ffi1) ffi.cdef(input) recomp = recompiler.Recompiler(ffi, 'testmod') recomp.collect_type_table() assert ''.join(map(str, recomp.cffi_types)) == expected_output
def test_struct_included(): baseffi = FFI() baseffi.cdef("struct foo_s { int x; };") baseffi.set_source('test_struct_included_base', None) # ffi = FFI() ffi.include(baseffi) target = udir.join('test_struct_included.py') make_py_source(ffi, 'test_struct_included', str(target)) assert target.read() == r"""# auto-generated file
def test_include_1b(): ffi1 = FFI() ffi1.cdef("int foo1(int);") lib1 = verify(ffi1, "test_include_1b_parent", "int foo1(int x) { return x + 10; }") ffi = FFI() ffi.include(ffi1) ffi.cdef("int foo2(int);") lib = verify(ffi, "test_include_1b", "int foo2(int x) { return x - 5; }") assert lib.foo2(42) == 37 assert lib.foo1(42) == 52 assert lib.foo1 is lib1.foo1
def test_include_3(): ffi1 = FFI() ffi1.cdef("typedef short sshort_t;") verify(ffi1, "test_include_3_parent", "typedef short sshort_t;") ffi = FFI() ffi.include(ffi1) ffi.cdef("sshort_t ff3(sshort_t);") lib = verify(ffi, "test_include_3", "typedef short sshort_t; //usually from a #include\n" "sshort_t ff3(sshort_t x) { return x + 42; }") assert lib.ff3(10) == 52 assert ffi.typeof(ffi.cast("sshort_t", 42)) is ffi.typeof("short") assert ffi1.typeof("sshort_t") is ffi.typeof("sshort_t")
def test_include_8(): ffi1 = FFI() ffi1.cdef("struct foo_s;") verify(ffi1, "test_include_8_parent", "struct foo_s;") ffi = FFI() ffi.include(ffi1) ffi.cdef("struct foo_s { int x, y; };") verify(ffi, "test_include_8", "struct foo_s { int x, y; };") e = py.test.raises(NotImplementedError, ffi.new, "struct foo_s *") assert str(e.value) == ( "'struct foo_s' is opaque in the ffi.include(), but no longer in " "the ffi doing the include (workaround: don't use ffi.include() but" " duplicate the declarations of everything using struct foo_s)")
def test_include_4(): ffi1 = FFI() ffi1.cdef("typedef struct { int x; } mystruct_t;") verify(ffi1, "test_include_4_parent", "typedef struct { int x; } mystruct_t;") ffi = FFI() ffi.include(ffi1) ffi.cdef("mystruct_t *ff4(mystruct_t *);") lib = verify(ffi, "test_include_4", "typedef struct {int x; } mystruct_t; //usually from a #include\n" "mystruct_t *ff4(mystruct_t *p) { p->x += 42; return p; }") p = ffi.new("mystruct_t *", [10]) q = lib.ff4(p) assert q == p assert p.x == 52 assert ffi1.typeof("mystruct_t") is ffi.typeof("mystruct_t")
def test_include_2(): ffi1 = FFI() ffi1.cdef("struct foo_s { int x, y; };") verify(ffi1, "test_include_2_parent", "struct foo_s { int x, y; };") ffi = FFI() ffi.include(ffi1) ffi.cdef("struct foo_s *ff2(struct foo_s *);") lib = verify(ffi, "test_include_2", "struct foo_s { int x, y; }; //usually from a #include\n" "struct foo_s *ff2(struct foo_s *p) { p->y++; return p; }") p = ffi.new("struct foo_s *") p.y = 41 q = lib.ff2(p) assert q == p assert p.y == 42 assert ffi1.typeof("struct foo_s") is ffi.typeof("struct foo_s")
def test_include_7(): ffi1 = FFI() ffi1.cdef("typedef ... mystruct_t;\n" "int ff7b(mystruct_t *);") verify(ffi1, "test_include_7_parent", "typedef struct { int x; } mystruct_t;\n" "int ff7b(mystruct_t *p) { return p->x; }") ffi = FFI() ffi.include(ffi1) ffi.cdef("mystruct_t *ff7(void);") lib = verify(ffi, "test_include_7", "typedef struct { int x; } mystruct_t; //usually from a #include\n" "static mystruct_t result_struct = { 42 };" "mystruct_t *ff7(void) { return &result_struct; }") p = lib.ff7() assert ffi.cast("int *", p)[0] == 42 assert lib.ff7b(p) == 42
def test_include_5(): ffi1 = FFI() ffi1.cdef("typedef struct { int x[2]; int y; } *mystruct_p;") verify(ffi1, "test_include_5_parent", "typedef struct { int x[2]; int y; } *mystruct_p;") ffi = FFI() ffi.include(ffi1) ffi.cdef("mystruct_p ff5(mystruct_p);") lib = verify(ffi, "test_include_5", "typedef struct {int x[2]; int y; } *mystruct_p; //usually #include\n" "mystruct_p ff5(mystruct_p p) { p->x[1] += 42; return p; }") assert ffi.alignof(ffi.typeof("mystruct_p").item) == 4 assert ffi1.typeof("mystruct_p") is ffi.typeof("mystruct_p") p = ffi.new("mystruct_p", [[5, 10], -17]) q = lib.ff5(p) assert q == p assert p.x[0] == 5 assert p.x[1] == 52 assert p.y == -17 assert ffi.alignof(ffi.typeof(p[0])) == 4
def test_include(): ffi = FFI() ffi.cdef("#define ABC 123") ffi.set_source('test_include', None) target = udir.join('test_include.py') make_py_source(ffi, 'test_include', str(target)) assert target.read() == r"""# auto-generated file import _cffi_backend ffi = _cffi_backend.FFI('test_include', _version = 0x2601, _types = b'', _globals = (b'\xFF\xFF\xFF\x1FABC',123,), ) """ # ffi2 = FFI() ffi2.include(ffi) target2 = udir.join('test2_include.py') make_py_source(ffi2, 'test2_include', str(target2)) assert target2.read() == r"""# auto-generated file
def test_include_1(): sub_ffi = FFI() sub_ffi.cdef("static const int k2 = 121212;") sub_ffi.include(original_ffi) assert 'macro FOOBAR' in original_ffi._parser._declarations assert 'macro FOOBAZ' in original_ffi._parser._declarations sub_ffi.set_source('re_python_pysrc', None) sub_ffi.emit_python_code(str(tmpdir.join('_re_include_1.py'))) # if sys.version_info[:2] >= (3, 3): import importlib importlib.invalidate_caches() # issue 197 (but can't reproduce myself) # from _re_include_1 import ffi assert ffi.integer_const('FOOBAR') == -42 assert ffi.integer_const('FOOBAZ') == -43 assert ffi.integer_const('k2') == 121212 lib = ffi.dlopen(extmod) # <- a random unrelated library would be fine assert lib.FOOBAR == -42 assert lib.FOOBAZ == -43 assert lib.k2 == 121212 # p = ffi.new("bar_t *", [5, b"foobar"]) assert p.a[4] == ord('a')
import os from os.path import join from typing import List import imm.build_ext import nmm.build_ext from cffi import FFI ffibuilder = FFI() libs = ["dcp"] ffibuilder.include(imm.build_ext.ffibuilder) ffibuilder.include(nmm.build_ext.ffibuilder) folder = os.path.dirname(os.path.abspath(__file__)) with open(join(folder, "deciphon.h"), "r") as f: ffibuilder.cdef(f.read()) extra_link_args: List[str] = [] if "DECIPHON_EXTRA_LINK_ARGS" in os.environ: extra_link_args += os.environ["DECIPHON_EXTRA_LINK_ARGS"].split(os.pathsep) ffibuilder.set_source( "deciphon._ffi", r""" #include "nmm/nmm.h" #include "dcp/dcp.h" """, libraries=libs, extra_link_args=extra_link_args,
sys.path.append(this_dir) from cairocffi import constants # Primary cffi definitions ffi = FFI() if hasattr(ffi, 'set_source'): # PyPy < 2.6 compatibility ffi.set_source('cairocffi._ffi', None) ffi.cdef(constants._CAIRO_HEADERS) # include xcffib cffi definitions for cairo xcb support try: from xcffib.ffi_build import ffi as xcb_ffi ffi.include(xcb_ffi) ffi.cdef(constants._CAIRO_XCB_HEADERS) except ImportError: pass # gdk pixbuf cffi definitions ffi_pixbuf = FFI() if hasattr(ffi_pixbuf, 'set_source'): # PyPy < 2.6 compatibility ffi_pixbuf.set_source('cairocffi._ffi_pixbuf', None) ffi_pixbuf.include(ffi) ffi_pixbuf.cdef(''' typedef unsigned long gsize; typedef unsigned int guint32; typedef unsigned int guint; typedef unsigned char guchar;
{ if (callback == NULL) { wlr_log_init(verbosity, NULL); } else { py_callback = callback; wlr_log_init(verbosity, wrapped_log_callback); } } """ include_dir = (Path(__file__).parent.parent / "include").resolve() assert include_dir.is_dir(), f"missing {include_dir}" ffi_builder = FFI() ffi_builder.set_source( "wlroots._ffi", SOURCE, libraries=["wlroots"], define_macros=[("WLR_USE_UNSTABLE", None)], include_dirs=["/usr/include/pixman-1", include_dir], ) ffi_builder.include(pywayland_ffi) ffi_builder.include(xkb_ffi) ffi_builder.cdef(CDEF) if __name__ == "__main__": ffi_builder.compile()
def setup_class(cls): try: from cffi import FFI # <== the system one, which from cffi import recompiler # needs to be at least cffi 1.0.0 from cffi import ffiplatform except ImportError: py.test.skip("system cffi module not found or older than 1.0.0") space = cls.space SRC = """ #define FOOBAR (-42) static const int FOOBAZ = -43; #define BIGPOS 420000000000L #define BIGNEG -420000000000L int add42(int x) { return x + 42; } int globalvar42 = 1234; const int globalconst42 = 4321; const char *const globalconsthello = "hello"; struct foo_s; typedef struct bar_s { int x; signed char a[]; } bar_t; enum foo_e { AA, BB, CC }; void init_test_re_python(void) { } /* windows hack */ void PyInit__test_re_python(void) { } /* windows hack */ """ tmpdir = udir.join('test_re_python') tmpdir.ensure(dir=1) c_file = tmpdir.join('_test_re_python.c') c_file.write(SRC) ext = ffiplatform.get_extension(str(c_file), '_test_re_python', export_symbols=[ 'add42', 'globalvar42', 'globalconst42', 'globalconsthello' ]) outputfilename = ffiplatform.compile(str(tmpdir), ext) cls.w_extmod = space.wrap(outputfilename) if WIN32: unicode_name = u'load\u03betest.dll' else: unicode_name = u'load_caf\xe9' + os.path.splitext( outputfilename)[1] try: unicode_name.encode(sys.getfilesystemencoding()) except UnicodeEncodeError: unicode_name = None # skip test_dlopen_unicode if unicode_name is not None: outputfileUname = os.path.join(unicode(udir), unicode_name) shutil.copyfile(outputfilename, outputfileUname) cls.w_extmodU = space.wrap(outputfileUname) #mod.tmpdir = tmpdir # ffi = FFI() ffi.cdef(""" #define FOOBAR -42 static const int FOOBAZ = -43; #define BIGPOS 420000000000L #define BIGNEG -420000000000L int add42(int); int globalvar42; const int globalconst42; const char *const globalconsthello = "hello"; int no_such_function(int); int no_such_globalvar; struct foo_s; typedef struct bar_s { int x; signed char a[]; } bar_t; enum foo_e { AA, BB, CC }; """) ffi.set_source('re_python_pysrc', None) ffi.emit_python_code(str(tmpdir.join('re_python_pysrc.py'))) # sub_ffi = FFI() sub_ffi.cdef("static const int k2 = 121212;") sub_ffi.include(ffi) assert 'macro FOOBAR' in ffi._parser._declarations assert 'macro FOOBAZ' in ffi._parser._declarations sub_ffi.set_source('re_py_subsrc', None) sub_ffi.emit_python_code(str(tmpdir.join('re_py_subsrc.py'))) # cls.w_fix_path = space.appexec([space.wrap(str(tmpdir))], """(path): def fix_path(ignored=None): import _cffi_backend # force it to be initialized import sys if path not in sys.path: sys.path.insert(0, path) return fix_path """)
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from cffi import FFI from xcffib.ffi_build import ffi as xcffib_ffi from cairocffi.ffi_build import ffi as cairocffi_ffi pango_ffi = FFI() # PyPy < 2.6 compatibility if hasattr(pango_ffi, 'set_source'): pango_ffi.set_source("xcffibaer_lib._ffi_pango", None) pango_ffi.include(cairocffi_ffi) pango_ffi.cdef(""" typedef ... PangoContext; typedef ... PangoLayout; typedef ... PangoFontDescription; typedef ... PangoAttrList; typedef enum { PANGO_ALIGN_LEFT, PANGO_ALIGN_CENTER, PANGO_ALIGN_RIGHT } PangoAlignment; typedef enum { PANGO_ELLIPSEIZE_NONE, PANGO_ELLIPSIZE_START, PANGO_ELLIPSIZE_MIDDLE,
from .. import _cffi, libnvpair from .._cffi import verify, boolean_t from cffi import FFI ffi = FFI() #ffi.include(_cffi.ffi) ffi.include(libnvpair.ffi)
from cffi import FFI import bsdopendirtype_build ffi = FFI() # ========== This is a demo of ffi.include() ========== ffi.include(bsdopendirtype_build.ffi) ffi.cdef(""" int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result); """) ffi.set_source("_recopendirtype", """ #include <sys/types.h> #include <dirent.h> """) if __name__ == '__main__': ffi.compile()
.indices = (uint8_t***)indices, .vals = (uint8_t*)vals, .vals_size = 5 }; return tensor; } taco_tensor_t* create_pointer_to_tensor() { taco_tensor_t* tensor = malloc(sizeof(taco_tensor_t)); *tensor = create_tensor(); return tensor; } """ ffi = FFI() ffi.include(tensor_cdefs) ffi.cdef(""" taco_tensor_t create_tensor(); taco_tensor_t* create_pointer_to_tensor(); """) ffi.set_source( 'taco_kernel', taco_define_header + taco_type_header + source, extra_compile_args=['-Wno-unused-variable', '-Wno-unknown-pragmas']) expected_tensor = Tensor.from_lol([[6, 0, 9, 8], [0, 0, 0, 0], [5, 0, 0, 7]], format='ds') with tempfile.TemporaryDirectory() as temp_dir: # Lock because FFI.compile is not thread safe: https://foss.heptapod.net/pypy/cffi/-/issues/490 with lock:
import constants # noqa # Create an empty _generated folder if needed shutil.rmtree((Path(__file__).parent / '_generated'), ignore_errors=True) (Path(__file__).parent / '_generated').mkdir(exist_ok=True) # Primary cffi definitions ffi = FFI() ffi.set_source('cairocffi._generated.ffi', None) ffi.cdef(constants._CAIRO_HEADERS) # include xcffib cffi definitions for cairo xcb support try: from xcffib.ffi_build import ffi as xcb_ffi ffi.include(xcb_ffi) ffi.cdef(constants._CAIRO_XCB_HEADERS) except ImportError: pass # gdk pixbuf cffi definitions ffi_pixbuf = FFI() ffi_pixbuf.set_source('cairocffi._generated.ffi_pixbuf', None) ffi_pixbuf.include(ffi) ffi_pixbuf.cdef(''' typedef unsigned long gsize; typedef unsigned int guint32; typedef unsigned int guint; typedef unsigned char guchar; typedef char gchar; typedef int gint;
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @authors Jean-Noel Quintin <*****@*****.**> @copyright 2013 Bull S.A.S. - All rights reserved.\n This is not Free or Open Source software.\n Please contact Bull SAS for details about its license.\n Bull - Rue Jean Jaurès - B.P. 68 - 78340 Les Clayes-sous-Bois @namespace bxi.base.builder cffi builder """ from cffi import FFI from bxi.base.cffi_builder import ffibuilder as base_ffibuilder import bxi.util_cffi_def as cdef libname = 'bxiutil' modulename = 'bxi.util.cffi_h' ffibuilder = FFI() ffibuilder.include(base_ffibuilder) ffibuilder.set_source(modulename, None, libraries=[libname ]) # or a list of libraries to link with ffibuilder.cdef(cdef.C_DEF) if __name__ == "__main__": ffibuilder.compile(verbose=True)
# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from cffi import FFI from cairocffi.ffi_build import ffi as cairocffi_ffi pango_ffi = FFI() pango_ffi.set_source("libqtile._ffi_pango", None) pango_ffi.include(cairocffi_ffi) pango_ffi.cdef(""" typedef ... PangoContext; typedef ... PangoLayout; typedef ... PangoFontDescription; typedef ... PangoAttrList; typedef enum { PANGO_ALIGN_LEFT, PANGO_ALIGN_CENTER, PANGO_ALIGN_RIGHT } PangoAlignment; typedef enum { PANGO_ELLIPSEIZE_NONE, PANGO_ELLIPSIZE_START, PANGO_ELLIPSIZE_MIDDLE,
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from cffi import FFI from xcffib.ffi_build import ffi as xcffib_ffi from cairocffi.ffi_build import ffi as cairocffi_ffi pango_ffi = FFI() pango_ffi.set_source("libqtile._ffi_pango", None) pango_ffi.include(cairocffi_ffi) pango_ffi.cdef(""" typedef ... PangoContext; typedef ... PangoLayout; typedef ... PangoFontDescription; typedef ... PangoAttrList; typedef enum { PANGO_ALIGN_LEFT, PANGO_ALIGN_CENTER, PANGO_ALIGN_RIGHT } PangoAlignment; typedef enum { PANGO_ELLIPSEIZE_NONE, PANGO_ELLIPSIZE_START, PANGO_ELLIPSIZE_MIDDLE,
# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from cffi import FFI from xcffib.ffi_build import ffi as xcffib_ffi xcursors_ffi = FFI() xcursors_ffi.set_source("libqtile.core._ffi_xcursors", None) xcursors_ffi.include(xcffib_ffi) xcursors_ffi.cdef(""" typedef uint32_t xcb_cursor_t; typedef struct xcb_cursor_context_t xcb_cursor_context_t; int xcb_cursor_context_new( xcb_connection_t *conn, xcb_screen_t *screen, xcb_cursor_context_t **ctx ); xcb_cursor_t xcb_cursor_load_cursor( xcb_cursor_context_t *ctx, const char *name );
libinput_device_config_scroll_set_button(struct libinput_device *device, uint32_t button); enum libinput_config_dwt_state { LIBINPUT_CONFIG_DWT_DISABLED, LIBINPUT_CONFIG_DWT_ENABLED, }; int libinput_device_config_dwt_is_available(struct libinput_device *device); enum libinput_config_status libinput_device_config_dwt_set_enabled(struct libinput_device *device, enum libinput_config_dwt_state enable); """ libinput_ffi = FFI() libinput_ffi.set_source( "libqtile.backend.wayland._libinput", "#include <libinput.h>\n" + wlr.SOURCE, libraries=["wlroots", "input"], define_macros=[("WLR_USE_UNSTABLE", None)], include_dirs=["/usr/include/pixman-1", wlr.include_dir], ) libinput_ffi.include(wlr.ffi_builder) libinput_ffi.cdef(CDEF) if __name__ == "__main__": libinput_ffi.compile()
def get_pango_context() -> Context: ffi = FFI() ffi.include(ffi_builder) ffi.cdef(''' /* Cairo */ typedef void cairo_t; typedef struct _cairo_surface cairo_surface_t; typedef enum _cairo_status { CAIRO_STATUS_SUCCESS = 0, CAIRO_STATUS_NO_MEMORY, CAIRO_STATUS_INVALID_RESTORE, CAIRO_STATUS_INVALID_POP_GROUP, CAIRO_STATUS_NO_CURRENT_POINT, CAIRO_STATUS_INVALID_MATRIX, CAIRO_STATUS_INVALID_STATUS, CAIRO_STATUS_NULL_POINTER, CAIRO_STATUS_INVALID_STRING, CAIRO_STATUS_INVALID_PATH_DATA, CAIRO_STATUS_READ_ERROR, CAIRO_STATUS_WRITE_ERROR, CAIRO_STATUS_SURFACE_FINISHED, CAIRO_STATUS_SURFACE_TYPE_MISMATCH, CAIRO_STATUS_PATTERN_TYPE_MISMATCH, CAIRO_STATUS_INVALID_CONTENT, CAIRO_STATUS_INVALID_FORMAT, CAIRO_STATUS_INVALID_VISUAL, CAIRO_STATUS_FILE_NOT_FOUND, CAIRO_STATUS_INVALID_DASH, CAIRO_STATUS_INVALID_DSC_COMMENT, CAIRO_STATUS_INVALID_INDEX, CAIRO_STATUS_CLIP_NOT_REPRESENTABLE, CAIRO_STATUS_TEMP_FILE_ERROR, CAIRO_STATUS_INVALID_STRIDE, CAIRO_STATUS_FONT_TYPE_MISMATCH, CAIRO_STATUS_USER_FONT_IMMUTABLE, CAIRO_STATUS_USER_FONT_ERROR, CAIRO_STATUS_NEGATIVE_COUNT, CAIRO_STATUS_INVALID_CLUSTERS, CAIRO_STATUS_INVALID_SLANT, CAIRO_STATUS_INVALID_WEIGHT, CAIRO_STATUS_INVALID_SIZE, CAIRO_STATUS_USER_FONT_NOT_IMPLEMENTED, CAIRO_STATUS_DEVICE_TYPE_MISMATCH, CAIRO_STATUS_DEVICE_ERROR, CAIRO_STATUS_INVALID_MESH_CONSTRUCTION, CAIRO_STATUS_DEVICE_FINISHED, CAIRO_STATUS_JBIG2_GLOBAL_MISSING, CAIRO_STATUS_PNG_ERROR, CAIRO_STATUS_FREETYPE_ERROR, CAIRO_STATUS_WIN32_GDI_ERROR, CAIRO_STATUS_TAG_ERROR, CAIRO_STATUS_LAST_STATUS } cairo_status_t; typedef cairo_status_t (*cairo_write_func_t) ( void * closure, const unsigned char *data, unsigned int length ); cairo_surface_t * cairo_pdf_surface_create_for_stream ( cairo_write_func_t write_func, void *closure, double width_in_points, double height_in_points ); void cairo_surface_destroy (cairo_surface_t *surface); cairo_t * cairo_create (cairo_surface_t *target); void cairo_destroy (cairo_t *cr); PangoContext * pango_cairo_create_context (cairo_t *cr); ''') ffi.set_source('pangocffi._generated.ffi', None) cairo = ffi.dlopen('cairo') pangocairo = ffi.dlopen('pangocairo-1.0') cairo_surface_t = cairo.cairo_pdf_surface_create_for_stream( ffi.NULL, ffi.NULL, 10, 10) cairo_t = cairo.cairo_create(cairo_surface_t) pango_pointer = pangocairo.pango_cairo_create_context(cairo_t) pango_pointer = pangocffi.ffi.cast('PangoContext *', pango_pointer) pango_pointer = pangocffi.ffi.gc(pango_pointer, pangocffi.gobject.g_object_unref) ContextCreator.cairo = cairo ContextCreator.cairo_surface_t = cairo_surface_t ContextCreator.cairo_t = cairo_t ContextCreator.pango_context = Context.from_pointer(pango_pointer) return ContextCreator.pango_context
Build the cffi bindings """ import sys from pathlib import Path from cffi import FFI from pangocffi import ffi as ffi_pango sys.path.append(str(Path(__file__).parent)) # Create an empty _generated folder if needed (Path(__file__).parent / '_generated').mkdir(exist_ok=True) # Read the CFFI definitions c_definitions_cairo_file = open( str(Path(__file__).parent / 'c_definitions_cairo.txt'), 'r') c_definitions_cairo = c_definitions_cairo_file.read() c_definitions_pangocairo_file = open( str(Path(__file__).parent / 'c_definitions_pangocairo.txt'), 'r') c_definitions_pangocairo = c_definitions_pangocairo_file.read() # cffi definitions, in the order outlined in: ffi = FFI() ffi.include(ffi_pango) ffi.set_source('pangocairocffi._generated.ffi', None) ffi.cdef(c_definitions_cairo) ffi.cdef(c_definitions_pangocairo) if __name__ == '__main__': ffi.compile()
from pathlib import Path from cffi import FFI from _hostlist_build import ffi as hostlist_ffi from _idset_build import ffi as idset_ffi ffi = FFI() ffi.include(hostlist_ffi) ffi.include(idset_ffi) ffi.set_source( "_flux._rlist", """ #include <jansson.h> #include <czmq.h> #include "src/common/librlist/rlist.h" // TODO: remove this when we can use cffi 1.10 #ifdef __GNUC__ #pragma GCC visibility push(default) #endif """, ) cdefs = """ typedef struct _zlistx_t zlistx_t; typedef struct _zhashx_t zhashx_t; typedef int... json_type; typedef struct json_t json_t;
import os.path import build_xlcall from cffi import FFI ffi = FFI() ffi.include(build_xlcall.ffi) ffi.cdef(''' typedef struct _IMAGE_EXPORT_DIRECTORY { DWORD Characteristics; DWORD TimeDateStamp; WORD MajorVersion; WORD MinorVersion; DWORD Name; DWORD Base; DWORD NumberOfFunctions; DWORD NumberOfNames; DWORD AddressOfFunctions; DWORD AddressOfNames; DWORD AddressOfNameOrdinals; } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY; DWORD pRVABase; IMAGE_EXPORT_DIRECTORY* pExportDirectory; void* PointerFromAddress(DWORD Address); DWORD AddressFromPointer(void* Pointer); ''') ffi.embedding_api('''
def prepare(space, cdef, module_name, source, w_includes=None, w_extra_source=None): try: import cffi from cffi import FFI # <== the system one, which from cffi import recompiler # needs to be at least cffi 1.0.4 from cffi import ffiplatform except ImportError: py.test.skip("system cffi module not found or older than 1.0.0") if cffi.__version_info__ < (1, 2, 0): py.test.skip("system cffi module needs to be at least 1.2.0") space.appexec([], """(): import _cffi_backend # force it to be initialized """) includes = [] if w_includes: includes += space.unpackiterable(w_includes) assert module_name.startswith('test_') module_name = '_CFFI_' + module_name rdir = udir.ensure('recompiler', dir=1) rdir.join('Python.h').write( '#define PYPY_VERSION XX\n' '#define PyMODINIT_FUNC /*exported*/ void\n' ) path = module_name.replace('.', os.sep) if '.' in module_name: subrdir = rdir.join(module_name[:module_name.index('.')]) os.mkdir(str(subrdir)) else: subrdir = rdir c_file = str(rdir.join('%s.c' % path)) ffi = FFI() for include_ffi_object in includes: ffi.include(include_ffi_object._test_recompiler_source_ffi) ffi.cdef(cdef) ffi.set_source(module_name, source) ffi.emit_c_code(c_file) base_module_name = module_name.split('.')[-1] sources = [] if w_extra_source is not None: sources.append(space.str_w(w_extra_source)) ext = ffiplatform.get_extension(c_file, module_name, include_dirs=[str(rdir)], export_symbols=['_cffi_pypyinit_' + base_module_name], sources=sources) ffiplatform.compile(str(rdir), ext) for extension in ['so', 'pyd', 'dylib']: so_file = str(rdir.join('%s.%s' % (path, extension))) if os.path.exists(so_file): break else: raise Exception("could not find the compiled extension module?") args_w = [space.wrap(module_name), space.wrap(so_file)] w_res = space.appexec(args_w, """(modulename, filename): import imp mod = imp.load_dynamic(modulename, filename) assert mod.__name__ == modulename return (mod.ffi, mod.lib) """) ffiobject = space.getitem(w_res, space.wrap(0)) ffiobject._test_recompiler_source_ffi = ffi if not hasattr(space, '_cleanup_ffi'): space._cleanup_ffi = [] space._cleanup_ffi.append(ffiobject) return w_res
# # [1]: https://groups.google.com/forum/#!topic/python-cffi/SPND0rRmazA # # This is not intended to be a complete cffi-based pango binding. from __future__ import print_function from cffi import FFI import xcffib import cairocffi import six ffi = FFI() ffi.include(xcffib.ffi) ffi.include(cairocffi.ffi) # pango/pangocairo ffi.cdef(""" typedef ... PangoContext; typedef ... PangoLayout; typedef ... PangoFontDescription; typedef ... PangoAttrList; typedef enum { PANGO_ALIGN_LEFT, PANGO_ALIGN_CENTER, PANGO_ALIGN_RIGHT } PangoAlignment; typedef enum { PANGO_ELLIPSEIZE_NONE,
def setup_class(cls): try: from cffi import FFI # <== the system one, which from cffi import recompiler # needs to be at least cffi 1.0.0 from cffi import ffiplatform except ImportError: py.test.skip("system cffi module not found or older than 1.0.0") space = cls.space SRC = """ #define FOOBAR (-42) static const int FOOBAZ = -43; #define BIGPOS 420000000000L #define BIGNEG -420000000000L int add42(int x) { return x + 42; } int globalvar42 = 1234; const int globalconst42 = 4321; const char *const globalconsthello = "hello"; struct foo_s; typedef struct bar_s { int x; signed char a[]; } bar_t; enum foo_e { AA, BB, CC }; void init_test_re_python(void) { } /* windows hack */ void PyInit__test_re_python(void) { } /* windows hack */ """ tmpdir = udir.join('test_re_python') tmpdir.ensure(dir=1) c_file = tmpdir.join('_test_re_python.c') c_file.write(SRC) ext = ffiplatform.get_extension(str(c_file), '_test_re_python', export_symbols=['add42', 'globalvar42', 'globalconst42', 'globalconsthello']) outputfilename = ffiplatform.compile(str(tmpdir), ext) cls.w_extmod = space.wrap(outputfilename) #mod.tmpdir = tmpdir # ffi = FFI() ffi.cdef(""" #define FOOBAR -42 static const int FOOBAZ = -43; #define BIGPOS 420000000000L #define BIGNEG -420000000000L int add42(int); int globalvar42; const int globalconst42; const char *const globalconsthello = "hello"; int no_such_function(int); int no_such_globalvar; struct foo_s; typedef struct bar_s { int x; signed char a[]; } bar_t; enum foo_e { AA, BB, CC }; """) ffi.set_source('re_python_pysrc', None) ffi.emit_python_code(str(tmpdir.join('re_python_pysrc.py'))) # sub_ffi = FFI() sub_ffi.cdef("static const int k2 = 121212;") sub_ffi.include(ffi) assert 'macro FOOBAR' in ffi._parser._declarations assert 'macro FOOBAZ' in ffi._parser._declarations sub_ffi.set_source('re_py_subsrc', None) sub_ffi.emit_python_code(str(tmpdir.join('re_py_subsrc.py'))) # space.appexec([space.wrap(str(tmpdir))], """(path): import _cffi_backend # force it to be initialized import sys sys.path.insert(0, path) """)