示例#1
0
文件: solver.py 项目: adwhit/opto
def solve_it(input_data):
    arr = [(int(n[0]), int(n[1])) for n in [line.split() for line in input_data.split("\n") if line]]
    nitems = arr[0][0]
    capacity = arr[0][1]
    values, weights = zip(*arr[1:])

    ffi = FFI()

    ffi.cdef("""
    typedef enum {false, true} bool;

    typedef struct {
        bool success;
        int value;
        bool *route;
    } Result;

    Result run(int *values, int *weights, int nitems, int capacity);
    """)

    fpath = "data/ks_4_0"

    lib = ffi.dlopen("libknap.so")
    res = lib.run(values, weights, nitems, capacity)

    out = "%d 1\n" % res.value
    out += " ".join([str(res.route[i]) for i in range(nitems)])

    return out
示例#2
0
def generate_tgl_update():
    from cffi import FFI
    ffi_ = FFI()
    ffi_.cdef("""int printf(const char *format, ...);""")
    C = ffi_.dlopen(None)

    cb = ffi.new('struct tgl_update_callback *')
    cb.new_msg = _tgl_upd_new_msg_cb
    cb.marked_read = _tgl_upd_marked_read_cb
    cb.logprintf = C.printf
    cb.type_notification = _tgl_upd_type_notification_cb
    cb.type_in_chat_notification = _tgl_upd_type_in_chat_notification_cb
    cb.type_in_secret_chat_notification = _tgl_upd_type_in_secret_chat_notification_cb
    cb.status_notification = _tgl_upd_status_notification_cb
    cb.user_registered = _tgl_upd_user_registered_cb
    cb.user_activated = _tgl_upd_user_activated_cb
    cb.new_authorization = _tgl_upd_new_authorization_cb
    cb.chat_update = _tgl_upd_chat_update_cb
    cb.user_update = _tgl_upd_user_update_cb
    cb.secret_chat_update = _tgl_upd_secret_chat_update_cb
    cb.msg_receive = _tgl_upd_msg_receive_cb
    cb.our_id = _tgl_upd_our_id_cb
    cb.notification = _tgl_upd_notification_cb
    cb.user_status_update = _tgl_upd_user_status_update_cb

    #use the default implementation
    #cb.create_print_name = _tgl_upd_create_print_name_cb

    return cb
示例#3
0
 def test_not_supported_bitfield_in_result(self):
     ffi = FFI(backend=self.Backend())
     ffi.cdef("struct foo_s { int a,b,c,d,e; int x:1; };")
     e = py.test.raises(NotImplementedError, ffi.callback,
                        "struct foo_s foo(void)", lambda: 42)
     assert str(e.value) == ("<struct foo_s(*)(void)>: "
         "cannot pass as argument or return value a struct with bit fields")
def test_win_common_types():
    from cffi.commontypes import COMMON_TYPES, _CACHE
    from cffi.commontypes import win_common_types, resolve_common_type

    #
    def clear_all(extra={}, old_dict=COMMON_TYPES.copy()):
        COMMON_TYPES.clear()
        COMMON_TYPES.update(old_dict)
        COMMON_TYPES.update(extra)
        _CACHE.clear()

    #
    for maxsize in [2 ** 32 - 1, 2 ** 64 - 1]:
        ct = win_common_types(maxsize)
        clear_all(ct)
        for key in sorted(ct):
            resolve_common_type(key)
    # assert did not crash
    # now try to use e.g. WPARAM (-> UINT_PTR -> unsigned 32/64-bit)
    for maxsize in [2 ** 32 - 1, 2 ** 64 - 1]:
        ct = win_common_types(maxsize)
        clear_all(ct)
        ffi = FFI()
        value = int(ffi.cast("WPARAM", -1))
        assert value == maxsize
    #
    clear_all()
示例#5
0
 def test_missing_function(self):
     ffi = FFI(backend=self.Backend())
     ffi.cdef("""
         int nonexistent();
     """)
     m = ffi.dlopen(lib_m)
     assert not hasattr(m, 'nonexistent')
示例#6
0
def build_ffi(include_recovery=False, include_schnorr=False, include_ecdh=False):
    ffi = FFI()

    source = "#include <secp256k1.h>"
    cdefs = definitions
    if include_recovery:
        cdefs += definitions_recovery
        source += "\n#include <secp256k1_recovery.h>"
    if include_schnorr:
        cdefs += definitions_schnorr
        source += "\n#include <secp256k1_schnorr.h>"
    if include_ecdh:
        cdefs += definitions_ecdh
        source += "\n#include <secp256k1_ecdh.h>"

    incpath = [os.environ['INCLUDE_DIR']] if 'INCLUDE_DIR' in os.environ else None
    libpath = [os.environ['LIB_DIR']] if 'LIB_DIR' in os.environ else None

    ffi.set_source(
        "_libsecp256k1",
        source,
        libraries=["secp256k1"],
        library_dirs=libpath,
        include_dirs=incpath)
    ffi.cdef(cdefs)

    return ffi
示例#7
0
def test_msobox_function_interface_on_ffcn_so_calling_ffcn(
    temp_mf_so_from_mf_f_file
):
    """."""
    # path to shared library
    so_path = str(temp_mf_so_from_mf_f_file)
    # print "so_path: ", so_path

    # load shared library as module
    module = import_shared_library(so_path)

    # initialize foreign function interface for library
    header = """
    void ffcn_(double *f, double *t, double *x, double *p, double *u);
    void ffcn_d_xpu_v_(
      double *f, double *f_d,
      double *t,
      double *x, double *x_d,
      double *p, double *p_d,
      double *u, double *u_d,
      int *nbdirs
    );
    """
    # open shared library
    ffi = FFI()
    ffi.cdef(header)
    module = ffi.dlopen(so_path)

    # function declaration and dimensions
    func = {
        "type": "ffcn",
        "name": "ffcn",
        "args": ["f", "t", "x", "p", "u"],
        "deriv": []
    }
    dims = {"f": 5, "t": 1, "x": 5, "p": 5, "u": 4}

    # create function
    ffcn = Function(module, dims, func, ffi=ffi, verbose=False)

    # define input values
    t = numpy.random.random(dims["t"])
    x = numpy.random.random(dims["x"])
    p = numpy.random.random(dims["p"])
    u = numpy.random.random(dims["u"])

    # define output variables
    desired = numpy.zeros(dims["f"])
    actual = numpy.zeros(dims["f"])

    # call functions
    ffcn(actual, t, x, p, u)
    ffcn_py(desired, t, x, p, u)

    # compare values
    print ""
    print "actual:  ", actual
    print "desired: ", desired
    print "error:   ", lg.norm(desired - actual)
    assert_allclose(actual, desired)
示例#8
0
def test_global_var_array():
    ffi = FFI()
    ffi.cdef("int a[100];")
    lib = verify(ffi, 'test_global_var_array', 'int a[100] = { 9999 };')
    lib.a[42] = 123456
    assert lib.a[42] == 123456
    assert lib.a[0] == 9999
示例#9
0
 def test_void_star_accepts_string(self):
     ffi = FFI(backend=self.Backend())
     ffi.cdef("""int strlen(const void *);""")
     needs_dlopen_none()
     lib = ffi.dlopen(None)
     res = lib.strlen(b"hello")
     assert res == 5
示例#10
0
 def test_not_supported_bitfield_in_result(self):
     ffi = FFI(backend=self.Backend())
     ffi.cdef("struct foo_s { int a,b,c,d,e; int x:1; };")
     e = py.test.raises(NotImplementedError, ffi.callback,
                        "struct foo_s foo(void)", lambda: 42)
     assert str(e.value) == ("struct foo_s(*)(): "
         "callback with unsupported argument or return type or with '...'")
示例#11
0
 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]")
示例#12
0
def test_no_args():
    ffi = FFI(backend=FakeBackend())
    ffi.cdef("""
        int foo(void);
        """)
    C = ffi.dlopen(None)
    assert C.foo.BType == '<func (), <int>, False>'
示例#13
0
 def test_ffi_new_allocator_2(self):
     ffi = FFI(backend=self.Backend())
     seen = []
     def myalloc(size):
         seen.append(size)
         return ffi.new("char[]", b"X" * size)
     def myfree(raw):
         seen.append(raw)
     alloc1 = ffi.new_allocator(myalloc, myfree)
     alloc2 = ffi.new_allocator(alloc=myalloc, free=myfree,
                                should_clear_after_alloc=False)
     p1 = alloc1("int[10]")
     p2 = alloc2("int[]", 10)
     assert seen == [40, 40]
     assert ffi.typeof(p1) == ffi.typeof("int[10]")
     assert ffi.sizeof(p1) == 40
     assert ffi.typeof(p2) == ffi.typeof("int[]")
     assert ffi.sizeof(p2) == 40
     assert p1[5] == 0
     assert p2[6] == ord('X') * 0x01010101
     raw1 = ffi.cast("char *", p1)
     raw2 = ffi.cast("char *", p2)
     del p1, p2
     retries = 0
     while len(seen) != 4:
         retries += 1
         assert retries <= 5
         import gc; gc.collect()
     assert seen == [40, 40, raw1, raw2]
     assert repr(seen[2]) == "<cdata 'char[]' owning 41 bytes>"
     assert repr(seen[3]) == "<cdata 'char[]' owning 41 bytes>"
示例#14
0
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>'
示例#15
0
def test_pipe():
    ffi = FFI(backend=FakeBackend())
    ffi.cdef("int pipe(int pipefd[2]);")
    C = ffi.dlopen(None)
    func = C.pipe
    assert func.name == 'pipe'
    assert func.BType == '<func (<pointer to <int>>), <int>, False>'
示例#16
0
def test_vararg():
    ffi = FFI(backend=FakeBackend())
    ffi.cdef("short foo(int, ...);")
    C = ffi.dlopen(None)
    func = C.foo
    assert func.name == 'foo'
    assert func.BType == '<func (<int>), <short>, True>'
示例#17
0
def test_unpack_args():
    ffi = FFI()
    ffi.cdef("void foo0(void); void foo1(int); void foo2(int, int);")
    lib = verify(ffi, "test_unpack_args", """
    void foo0(void) { }
    void foo1(int x) { }
    void foo2(int x, int y) { }
    """)
    assert 'foo0' in repr(lib.foo0)
    assert 'foo1' in repr(lib.foo1)
    assert 'foo2' in repr(lib.foo2)
    lib.foo0()
    lib.foo1(42)
    lib.foo2(43, 44)
    e1 = py.test.raises(TypeError, lib.foo0, 42)
    e2 = py.test.raises(TypeError, lib.foo0, 43, 44)
    e3 = py.test.raises(TypeError, lib.foo1)
    e4 = py.test.raises(TypeError, lib.foo1, 43, 44)
    e5 = py.test.raises(TypeError, lib.foo2)
    e6 = py.test.raises(TypeError, lib.foo2, 42)
    e7 = py.test.raises(TypeError, lib.foo2, 45, 46, 47)
    assert str(e1.value) == "foo0() takes no arguments (1 given)"
    assert str(e2.value) == "foo0() takes no arguments (2 given)"
    assert str(e3.value) == "foo1() takes exactly one argument (0 given)"
    assert str(e4.value) == "foo1() takes exactly one argument (2 given)"
    assert str(e5.value) == "foo2() takes exactly 2 arguments (0 given)"
    assert str(e6.value) == "foo2() takes exactly 2 arguments (1 given)"
    assert str(e7.value) == "foo2() takes exactly 2 arguments (3 given)"
示例#18
0
文件: api.py 项目: julienc91/pystassh
def _init_api():

    lib_name = ctypes.util.find_library("ssh")
    if not lib_name:
        raise exceptions.PystasshException("libssh not found, please visit https://www.libssh.org/get-it/")

    ffi = FFI()
    lib = ffi.dlopen(lib_name)
    ffi.cdef("""
        void* ssh_new();
        int ssh_options_set(void*, int, char*);
        int ssh_connect(void*);
        int ssh_disconnect(void*);
        int ssh_is_connected(void*);
        char* ssh_get_error(void*);

        int ssh_userauth_password(void*, char*, char*);
        int ssh_userauth_autopubkey(void*, char*);

        void* ssh_channel_new(void*);
        int ssh_channel_open_session(void*);
        int ssh_channel_is_open(void*);
        void ssh_channel_free(void*);
        int ssh_channel_request_exec(void*, char*);
        int ssh_channel_request_pty(void*);
        int ssh_channel_request_shell(void*);

        int ssh_channel_get_exit_status(void*);
        int ssh_channel_read(void*, char*, int, int);
        int ssh_channel_send_eof(void*);
    """)
    return ffi, lib
示例#19
0
def test_verify_anonymous_struct_with_star_typedef():
    ffi = FFI()
    ffi.cdef("typedef struct { int a; long b; } *foo_t;")
    verify(ffi, 'test_verify_anonymous_struct_with_star_typedef',
           "typedef struct { int a; long b; } *foo_t;")
    p = ffi.new("foo_t", {'b': 42})
    assert p.b == 42
示例#20
0
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)]
示例#21
0
文件: ca.py 项目: delroth/sslenroll
def netscape_spki_from_b64(b64):
    """Converts a base64 encoded Netscape SPKI DER to a crypto.NetscapeSPKI.

    PyOpenSSL does not yet support doing that by itself, so some work around
    through FFI and "internals-patching" trickery is required to perform this
    conversion. https://github.com/pyca/pyopenssl/issues/177 tracks the issue
    upstream.
    """
    if not hasattr(netscape_spki_from_b64, 'NETSCAPE_SPKI_b64_decode'):
        from cffi import FFI as CFFI
        from OpenSSL._util import ffi as _sslffi, lib as _ssllib
        cffi = CFFI()
        cffi.cdef('void* NETSCAPE_SPKI_b64_decode(const char *str, int len);')
        lib = cffi.dlopen('libssl.so')
        def wrapper(b64, lib=lib):
            if isinstance(b64, str):
                b64 = b64.encode('ascii')
            b64_ptr = _sslffi.new('char[]', b64)
            spki_obj = lib.NETSCAPE_SPKI_b64_decode(b64_ptr, len(b64))
            if spki_obj == cffi.NULL:
                raise ValueError("Invalid SPKI base64")
            def free(spki_obj, ref=b64_ptr):
                _ssllib.NETSCAPE_SPKI_free(spki_obj)
            return _sslffi.gc(spki_obj, free)
        netscape_spki_from_b64.func = wrapper

    ret = crypto.NetscapeSPKI()
    ret._spki = netscape_spki_from_b64.func(b64)
    return ret
示例#22
0
def load_inline_module():
    """
    Create an inline module, return the corresponding ffi and dll objects.
    """
    from cffi import FFI

    # We can't rely on libc availability on Windows anymore, so we use our
    # own compiled wrappers (see https://bugs.python.org/issue23606).

    defs = """
    double _numba_test_sin(double x);
    double _numba_test_cos(double x);
    int foo(int a, int b, int c);
    """

    source = """
    static int foo(int a, int b, int c)
    {
        return a + b * c;
    }
    """

    ffi = FFI()
    ffi.cdef(defs)
    # Load the _helperlib namespace
    from numba import _helperlib
    return ffi, ffi.dlopen(_helperlib.__file__)
 def test_load_library(self):
     ffi = FFI()
     ffi.cdef("double sin(double x);")
     csrc = '/*hi there %s!3*/\n#include <math.h>\n' % self
     v = Verifier(ffi, csrc, force_generic_engine=self.generic)
     library = v.load_library()
     assert library.sin(12.3) == math.sin(12.3)
示例#24
0
文件: __init__.py 项目: adilger/zfs
def _setup_cffi():
    class LazyLibrary(object):

        def __init__(self, ffi, libname):
            self._ffi = ffi
            self._libname = libname
            self._lib = None
            self._lock = threading.Lock()

        def __getattr__(self, name):
            if self._lib is None:
                with self._lock:
                    if self._lib is None:
                        self._lib = self._ffi.dlopen(self._libname)

            return getattr(self._lib, name)

    MODULES = ["libnvpair", "libzfs_core"]
    ffi = FFI()

    for module_name in MODULES:
        module = importlib.import_module("." + module_name, __package__)
        ffi.cdef(module.CDEF)
        lib = LazyLibrary(ffi, module.LIBRARY)
        setattr(module, "ffi", ffi)
        setattr(module, "lib", lib)
示例#25
0
def test_bad_size_of_global_2():
    ffi = FFI()
    ffi.cdef("int glob[10];")
    lib = verify(ffi, "test_bad_size_of_global_2", "int glob[9];")
    e = py.test.raises(ffi.error, "lib.glob")
    assert str(e.value) == ("global variable 'glob' should be 40 bytes "
                            "according to the cdef, but is actually 36")
示例#26
0
class Binding(object):
    def __init__(self, extra_objects=None, include_dirs=None, libraries=None):
        self.ffi = FFI()
        self.ffi.cdef(cdef)
        self._lib = None
        if extra_objects is None:
            extra_objects = []
        self._extra_objects = extra_objects
        if include_dirs is None:
            include_dirs = []
        self._include_dirs = include_dirs
        if libraries is None:
            libraries = ["fuzzy"]
        self._libraries = libraries

    def verify(self):
        self._lib = self.ffi.verify(
            source,
            ext_package="ssdeep",
            extra_objects=self._extra_objects,
            include_dirs=self._include_dirs,
            modulename=_create_modulename(cdef, source, __version__),
            libraries=self._libraries,
        )

    @property
    def lib(self):
        if self._lib is None:
            self.verify()
        return self._lib
示例#27
0
 def test_tag(self):
     ffi = FFI()
     ffi.cdef("/* %s test_tag */ double test1tag(double x);" % self)
     csrc = "double test1tag(double x) { return x - 42.0; }"
     lib = ffi.verify(csrc, force_generic_engine=self.generic,
                      tag='xxtest_tagxx')
     assert lib.test1tag(143) == 101.0
     assert '_cffi_xxtest_tagxx_' in ffi.verifier.modulefilename
示例#28
0
文件: cffi_.py 项目: zhaozw/hall37
def loadCffi(libname, cdef_text, libpath):
    if libname in _ft_cffi:
        return _ft_cffi[libname]
    _ffi = FFI()
    _ffi.cdef(cdef_text)
    sofile = libpath + "/" + libname + ".so"
    _lib = _ffi.dlopen(sofile)
    _ft_cffi[libname] = (_lib, _ffi)
示例#29
0
 def test_name_from_checksum_of_csrc(self):
     names = []
     for csrc in ['123', '123', '1234']:
         ffi = FFI()
         ffi.cdef("double sin(double x);")
         v = Verifier(ffi, csrc, force_generic_engine=self.generic)
         names.append(v.get_module_name())
     assert names[0] == names[1] != names[2]
示例#30
0
 def test_dlopen_flags(self):
     ffi = FFI(backend=self.Backend())
     ffi.cdef("""
         double cos(double x);
     """)
     m = ffi.dlopen(lib_m, ffi.RTLD_LAZY | ffi.RTLD_LOCAL)
     x = m.cos(1.23)
     assert x == math.cos(1.23)
示例#31
0
from cffi import FFI
ffibuilder = FFI()

ffibuilder.set_source("_libtyro", 
    # """ """,
    """
        typedef void** Tyro;
        
        Tyro new_tyro(void);
        void set_encoder_ranges(Tyro, double[], double[], int);
        void push_vec_frame(Tyro, void*, int, long[2]);
        void cycle(Tyro);
        void print_array_f64(double[], int);
        void print_array(double[], int, long[2]);
        float add_reward(Tyro, float);
        float get_reward(Tyro);
        int add_100(Tyro, int);
        void drop_tyro(Tyro);
    """,
    libraries=['tyro'])
    # include_dirs=['/usr/'])

ffibuilder.cdef("""
    typedef void** Tyro;

    Tyro new_tyro(void);
    void set_encoder_ranges(Tyro, double[], double[], int);
    void push_vec_frame(Tyro, void*, int, long[2]);
    void cycle(Tyro);    
    void print_array_f64(double[], int);
    void print_array(double[], int, long[2]);
示例#32
0
#!/usr/bin/env python

import os
from cffi import FFI

COMPILE = True
CORE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',
                        'core')

ffi = FFI()

if COMPILE:
    ffi.set_source(
        "_core", """
            #include "cwrapper.h"
        """,
        libraries=['run_rabbit_run'],
        library_dirs=[os.path.join(CORE_DIR, 'build')],
        include_dirs=[os.path.join(CORE_DIR, 'include')]
    )

ffi.cdef("""
    typedef struct Core Core;

    Core* NewCore(void);
    void Core_Init(Core *c, const char *shaderPath, const char *imagePath);
    void Core_Run(Core *c);
    void DeleteCore(Core *c);
""")

if not COMPILE:
示例#33
0
 def test_explicit_cdecl_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")
     win64 = (sys.maxsize > 2**32)
     #
     ffi = FFI(backend=self.Backend())
     ffi.cdef("""
         BOOL QueryPerformanceFrequency(LONGLONG *lpFrequency);
     """)
     m = ffi.dlopen("Kernel32.dll")
     tp = ffi.typeof(m.QueryPerformanceFrequency)
     assert str(tp) == "<ctype 'int(*)(long long *)'>"
     #
     ffi = FFI(backend=self.Backend())
     ffi.cdef("""
         BOOL __cdecl QueryPerformanceFrequency(LONGLONG *lpFrequency);
     """)
     m = ffi.dlopen("Kernel32.dll")
     tpc = ffi.typeof(m.QueryPerformanceFrequency)
     assert tpc is tp
     #
     ffi = FFI(backend=self.Backend())
     ffi.cdef("""
         BOOL WINAPI QueryPerformanceFrequency(LONGLONG *lpFrequency);
     """)
     m = ffi.dlopen("Kernel32.dll")
     tps = ffi.typeof(m.QueryPerformanceFrequency)
     if win64:
         assert tps is tpc
     else:
         assert tps is not tpc
         assert str(tps) == "<ctype 'int(__stdcall *)(long long *)'>"
     #
     ffi = FFI(backend=self.Backend())
     ffi.cdef("typedef int (__cdecl *fnc_t)(int);")
     ffi.cdef("typedef int (__stdcall *fns_t)(int);")
     tpc = ffi.typeof("fnc_t")
     tps = ffi.typeof("fns_t")
     assert str(tpc) == "<ctype 'int(*)(int)'>"
     if win64:
         assert tps is tpc
     else:
         assert str(tps) == "<ctype 'int(__stdcall *)(int)'>"
     #
     fnc = ffi.cast("fnc_t", 0)
     fns = ffi.cast("fns_t", 0)
     ffi.new("fnc_t[]", [fnc])
     if not win64:
         py.test.raises(TypeError, ffi.new, "fnc_t[]", [fns])
         py.test.raises(TypeError, ffi.new, "fns_t[]", [fnc])
     ffi.new("fns_t[]", [fns])
示例#34
0
from cffi import FFI

CDEF = '''\
typedef unsigned char uuid_t[16];

void uuid_generate(uuid_t out);
'''

ffibuilder = FFI()
ffibuilder.cdef(CDEF)
ffibuilder.set_source(
    '_uuidcffi',
    '#include <uuid/uuid.h>',
    libraries=['uuid'],
)
示例#35
0
import os.path
from cffi import FFI

ffibuilder = FFI()

proto = open("cffi-proto.h", 'r').read()
ffibuilder.cdef(
    proto +
    '\n extern "Python" void pysimul_regular_callback_f(uint64_t, size_t, double);'
)
ffibuilder.set_source("pysimul_ffi",
                      proto,
                      extra_objects=[os.path.abspath("./libpysimul.so")])

if __name__ == "__main__":
    ffibuilder.compile(verbose=True)
#!/usr/bin/python3
# encoding: utf-8

import os
import subprocess
from cffi import FFI

ffi = FFI()
filedir = os.path.dirname(os.path.abspath(__file__))
libpath = os.path.join(filedir, '..', '..', 'build')
libltfat = os.path.join(libpath, 'libltfat.so')
header = os.path.join(libpath, 'ltfat_flat.h')

with open(header) as f_header:
    ffi.cdef(f_header.read())

lib = ffi.dlopen(libltfat)

示例#37
0
ceres_include='./include'          # contains Ceres/ceres.h
ceres_library='./lib/libceres.so'
eigen_include='./include/eigen3'                     # contains Eigen/Core
glog_library='./lib/libglog.so'
cuda_include='/usr/local/cuda-10.0/include'
cudart = '/usr/local/cuda-10.0/lib64/libcudart.so'

os.system('gcc -shared src/mesh_rasterization.cpp -c -o src/mesh_rasterization.cpp.o -fopenmp -fPIC -O2 -std=c++11')
os.system('gcc -shared src/farthest_point_sampling.cpp -c -o src/farthest_point_sampling.cpp.o -fopenmp -fPIC -O2 -std=c++11')
os.system('gcc -shared src/uncertainty_pnp.cpp -c -o src/uncertainty_pnp.cpp.o -fopenmp -fPIC -O2 -std=c++11 -I {} -I {}'.
          format(ceres_include,eigen_include))
os.system('nvcc src/nearest_neighborhood.cu -c -o src/nearest_neighborhood.cu.o -x cu -Xcompiler -fPIC -O2 -arch=sm_52 -I {} -D_FORCE_INLINES'.
          format(cuda_include))

from cffi import FFI
ffibuilder = FFI()


# cdef() expects a string listing the C types, functions and
# globals needed from Python. The string follows the C syntax.
with open(os.path.join(os.path.dirname(__file__), "src/utils_python_binding.h")) as f:
    ffibuilder.cdef(f.read())

ffibuilder.set_source("_extend_utils",
                      """
                             #include "src/utils_python_binding.h"   // the C header of the library
                      """,
                      extra_objects=['src/mesh_rasterization.cpp.o','src/farthest_point_sampling.cpp.o',
                                     'src/uncertainty_pnp.cpp.o','src/nearest_neighborhood.cu.o',
                                     # 'src/post_process.cpp.o',
                                     ceres_library, glog_library,
示例#38
0
from random import shuffle

from cffi import FFI

ffi = FFI()

ffi.cdef("""
void qsort(void *base, size_t nel, size_t width,
            int (*compar)(const void *, const void *));
""")
C = ffi.dlopen(None)


@ffi.callback("int(void*, void*)")
def cffi_int_compare(a, b):
    int_a = ffi.cast('int*', a)[0]
    int_b = ffi.cast('int*', b)[0]
    print(f" {int_a} cmp {int_b}")
    return int_a - int_b


def main():
    numbers = list(range(5))
    shuffle(numbers)
    print(f"shuffled: {numbers}")

    c_array = ffi.new("int[]", numbers)

    C.qsort(
        c_array,
        len(c_array),
示例#39
0
import os
import math
import json
import re
import subprocess
from multiprocessing import Process, Pipe
from cffi import FFI
import site
"""
sudo apt-get install python-pip
sudo apt-get install libffi-dev
sudo pip install cffi
sudo apt-get install python3-cffi
"""

ffi = FFI()
cpp_out = subprocess.check_output(["cpp",
                                   "../src/ems_proto.h"]).decode("utf-8")
prototypes = cpp_out.split("\n")
headerLines = []
for line in prototypes:
    # Strip CPP directives and annotations
    line = re.sub("^#.*$", "", line)
    # Strip extern attribute
    line = re.sub("extern \"C\" ", "", line)
    if line is not "":
        headerLines.append(line)

# Delcare the CFFI Headers
ffi.cdef('\n'.join(headerLines))
示例#40
0
    def get_ffi(self, src=c_source):
        from cffi import FFI

        ffi = FFI()
        ffi.cdef(src)
        return ffi
示例#41
0
from enum import Enum
from time import sleep
import os.path
from cffi import FFI
from nicelib import NiceLib, NiceObjectDef
from . import Motion
from .. import _ParamDict
from ... import Q_
from ...errors import InstrumentTypeError, Error
from ..util import check_units, check_enums

FILTER_FLIPPER_TYPE = 37

lib_name = 'Thorlabs.MotionControl.FilterFlipper.dll'

ffi = FFI()
ffi.cdef("""
    typedef struct tagSAFEARRAYBOUND {
      ULONG cElements;
      LONG  lLbound;
    } SAFEARRAYBOUND, *LPSAFEARRAYBOUND;    
        
        typedef struct tagSAFEARRAY {
      USHORT         cDims;
      USHORT         fFeatures;
      ULONG          cbElements;
      ULONG          cLocks;
      PVOID          pvData;
      SAFEARRAYBOUND rgsabound[1];
    } SAFEARRAY, *LPSAFEARRAY;
""")
示例#42
0
文件: schtest.py 项目: JdeH/pytigon
from cffi import FFI

ffi = FFI()

ffi.cdef("""
long long silnia(long long l);
char * passed(char * arg);
int free_memory(void *ptr);
void message(char * msg);
""")

C = ffi.dlopen(__file__.replace('.py','.bin'))

def silnia(l):
    ret = C.silnia(l)
    return ret

def passed(arg):
    buf = C.passed(arg.encode('utf-8'))
    ret = ffi.string(buf).decode('utf-8')
    C.free_memory(buf)
    return ret

def message(msg):
    C.message(msg.encode('utf-8'))
示例#43
0
import os

from cffi import FFI

header_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..",
                           "data", "vosk", "vosk_api.h")

_ffi = FFI()
with open(header_file, "r") as f:
    _ffi.cdef(f.read())
_vosk_lib = _ffi.dlopen("libvosk.so")
#
# from ctypes import cdll
# _vosk_lib = cdll.LoadLibrary()
# print("vosk lib: %s" % _vosk_lib)


class Model(object):
    def __init__(self, model_path):
        self._handle = _vosk_lib.vosk_model_new(model_path.encode('utf-8'))

    def __del__(self):
        _vosk_lib.vosk_model_free(self._handle)

    def vosk_model_find_word(self, word):
        return _vosk_lib.vosk_model_find_word(self._handle,
                                              word.encode('utf-8'))


class SpkModel(object):
    def __init__(self, model_path):
示例#44
0
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
"""Example of interaction between C code and numpy using cffi

@author: Nicolas Iooss
"""
from cffi import FFI
import numpy
import os
import os.path
import sys

ffi = FFI()
SIZEOF_DOUBLE = ffi.sizeof('double')
current_dir = os.path.dirname(__file__) or os.path.curdir
with open(os.path.join(current_dir, 'cffi_example.h'), 'r') as fhead:
    ffi.cdef(''.join([
        line.replace('CFFI_EXAMPLE_API', '') for line in fhead
        if not line.lstrip().startswith('#')
    ]))
filepath = os.path.join(current_dir, '_cffi_example')
if os.name == 'nt':
    filepath += '.dll'
elif os.name == 'posix':
    filepath += '.so'
else:
    raise RuntimeError("Unknown OS {}".format(os.name))

env_cc = os.environ.get('CC')
if env_cc and (' -m32' in env_cc or ' -m64' in env_cc):
    try:
示例#45
0
from cffi import FFI

ffi = FFI()

ffi.cdef("""
    int add(int, int);
""")

C = ffi.dlopen("./libsimp.so")

print(C.add(2, 3))
示例#46
0
from cffi import FFI

__all__ = [
    'Security',
    'version',
    'version_info',
]

version = platform.mac_ver()[0]
version_info = tuple(map(int, version.split('.')))

if version_info < (10, 7):
    raise OSError('Only OS X 10.7 and newer are supported, not %s.%s' %
                  (version_info[0], version_info[1]))

ffi = FFI()
ffi.cdef("""
    typedef bool Boolean;
    typedef long CFIndex;
    typedef int32_t OSStatus;
    typedef unsigned long CFTypeID;
    typedef uint32_t SecTrustSettingsDomain;
    typedef uint32_t SecPadding;
    typedef uint32_t SecItemImportExportFlags;
    typedef uint32_t SecKeyImportExportFlags;
    typedef uint32_t SecExternalFormat;
    typedef uint32_t SecExternalItemType;
    typedef uint32_t CSSM_ALGORITHMS;
    typedef uint64_t CSSM_CC_HANDLE;
    typedef uint32_t CSSM_KEYUSE;
    typedef uint32_t CSSM_CERT_TYPE;
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os.path

from cffi import FFI

INCLUDE_DIR = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    "libpicohttpparser",
)

ffi = FFI()
ffi.set_source(
    "_picohttpparser",
    " #include <picohttpparser.h> ",
    include_dirs=[INCLUDE_DIR],
    libraries=["libpicohttpparser"],
)
ffi.cdef("""

    struct phr_header {
        const char *name;
        size_t name_len;
        const char *value;
        size_t value_len;
    };
示例#48
0
from cffi import FFI
ffi = FFI()

ffi.cdef("""
typedef struct t_point t_point;
struct t_point 
{
  double x;
  double y;
};

typedef struct t_test t_test;

struct t_test {
  char *sentence;
  int  nb_points;
  t_point *points;
  double *distances;
}; 

char * increment_string(char *str, int n);
void generate_points(t_test * test, int nb);
void distance_between_points(t_test *test);

""")

if __name__ == '__main__':
    # Load C shared libray
    lib = ffi.dlopen('./libblog.so')

    # Declare the C structure
示例#49
0
from nss.error import NSPRError
from pyasn1.error import PyAsn1Error
from six.moves import urllib

from ipapython.ipa_log_manager import root_logger, log_mgr
from ipapython import ipautil
import ipapython.errors

from ipaplatform.constants import constants
from ipaplatform.paths import paths
from ipaplatform.redhat.authconfig import RedHatAuthConfig
from ipaplatform.base.tasks import BaseTaskNamespace

from ipalib.constants import IPAAPI_USER

_ffi = FFI()
_ffi.cdef("""
int rpmvercmp (const char *a, const char *b);
""")

# use ctypes loader to get correct librpm.so library version according to
# https://cffi.readthedocs.org/en/latest/overview.html#id8
_librpm = _ffi.dlopen(find_library("rpm"))

log = log_mgr.get_logger(__name__)


def selinux_enabled():
    """
    Check if SELinux is enabled.
    """
示例#50
0
    def test_dlopen_handle(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("uses 'dl' explicitly")
        if self.__class__.Backend is CTypesBackend:
            py.test.skip("not for the ctypes backend")
        backend = self.Backend()
        ffi1 = FFI(backend=backend)
        ffi1.cdef("""void *dlopen(const char *filename, int flags);
                     int dlclose(void *handle);""")
        lib1 = ffi1.dlopen('dl')
        handle = lib1.dlopen(self.module.encode(sys.getfilesystemencoding()),
                             backend.RTLD_LAZY)
        assert ffi1.typeof(handle) == ffi1.typeof("void *")
        assert handle

        ffi = FFI(backend=backend)
        ffi.cdef("""unsigned short foo_2bytes(unsigned short a);""")
        lib = ffi.dlopen(handle)
        x = lib.foo_2bytes(1000)
        assert x == 1042

        err = lib1.dlclose(handle)
        assert err == 0
示例#51
0
 def test_vararg(self):
     if not sys.platform.startswith('linux'):
         py.test.skip("probably no symbol 'stderr' in the lib")
     ffi = FFI(backend=self.Backend())
     ffi.cdef("""
        int fprintf(void *, const char *format, ...);
        void *stderr;
     """)
     needs_dlopen_none()
     ffi.C = ffi.dlopen(None)
     with FdWriteCapture() as fd:
         ffi.C.fprintf(ffi.C.stderr, b"hello with no arguments\n")
         ffi.C.fprintf(ffi.C.stderr,
                       b"hello, %s!\n", ffi.new("char[]", b"world"))
         ffi.C.fprintf(ffi.C.stderr,
                       ffi.new("char[]", b"hello, %s!\n"),
                       ffi.new("char[]", b"world2"))
         ffi.C.fprintf(ffi.C.stderr,
                       b"hello int %d long %ld long long %lld\n",
                       ffi.cast("int", 42),
                       ffi.cast("long", 84),
                       ffi.cast("long long", 168))
         ffi.C.fprintf(ffi.C.stderr, b"hello %p\n", ffi.NULL)
     res = fd.getvalue()
     assert res == (b"hello with no arguments\n"
                    b"hello, world!\n"
                    b"hello, world2!\n"
                    b"hello int 42 long 84 long long 168\n"
                    b"hello (nil)\n")
示例#52
0
 def test_addressof_lib(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 implemented with the ctypes backend")
     ffi = FFI(backend=self.Backend())
     ffi.cdef("extern long left; int test_getting_errno(void);")
     lib = ffi.dlopen(self.module)
     lib.left = 123456
     p = ffi.addressof(lib, "left")
     assert ffi.typeof(p) == ffi.typeof("long *")
     assert p[0] == 123456
     p[0] += 1
     assert lib.left == 123457
     pfn = ffi.addressof(lib, "test_getting_errno")
     assert ffi.typeof(pfn) == ffi.typeof("int(*)(void)")
     assert pfn == lib.test_getting_errno
示例#53
0
# pylint: disable = invalid-name
"""Build helper for C++ extension module used to solve the equation system"""

import os.path
from cffi import FFI

here = os.path.abspath(os.path.dirname(__file__))
ffibuilder = FFI()
with open(os.path.join(here, 'solver.cpp')) as cpp:
    ffibuilder.set_source(
        'lib_solver',
        cpp.read(),
        source_extension='.cpp',
        libraries=['gmp', 'flint'],
    )
ffibuilder.cdef("""
    int solve(char* out_messages[], const char* prime, 
              const char* sums[], size_t n);
""")

if __name__ == '__main__':
    ffibuilder.compile(verbose=True)
示例#54
0
class _PcapFfi(object):
    """ This class represents the low-level interface to the libpcap library. It encapsulates all the cffi calls
        and C/Python conversions, as well as translation of errors and error codes to PcapExceptions.  It is intended
        to be used as a singleton class through the PcapDumper and PcapLiveDevice classes, below. """
    _instance = None
    __slots__ = ['_ffi', '_libpcap', '_interfaces', '_windows']

    def __init__(self):
        """ Assumption: this class is instantiated once in the main thread before any other threads have a chance
            to try instantiating it. """
        if _PcapFfi._instance:
            raise Exception("Can't initialize this class more than once!")

        _PcapFfi._instance = self
        self._windows = False
        self._ffi = FFI()
        self._ffi.cdef(cc_ndpi_network_headers, override=True, packed=True)
        if "win" in sys.platform[:3]:
            raise PcapException('Windows OS is not currently supported.')
        elif sys.platform == 'darwin':
            self._ffi.cdef(cc_libpcap_structure, override=True)
            libname = '/libs/libpcap.so'
        else:
            self._ffi.cdef(cc_libpcap_structure, override=True)
            libname = '/libs/libpcap.so'
        try:
            self._ffi.cdef(cc_libpcap_apis, override=True)
            self._libpcap = self._ffi.dlopen(
                dirname(abspath(__file__)) + libname)
        except Exception as e:
            raise PcapException("Error opening libpcap: {}".format(e))

        self._interfaces = []
        self.discoverdevs()

    @staticmethod
    def instance():
        if not _PcapFfi._instance:
            _PcapFfi._instance = _PcapFfi()
        return _PcapFfi._instance

    @property
    def version(self):
        return self._ffi.string(self._libpcap.pcap_lib_version())

    def discoverdevs(self):
        """ Find all the pcap-eligible devices on the local system """
        if len(self._interfaces):
            raise PcapException("Device discovery should only be done once.")

        ppintf = self._ffi.new("pcap_if_t * *")
        errbuf = self._ffi.new("char []", 128)
        rv = self._libpcap.pcap_findalldevs(ppintf, errbuf)
        if rv:
            raise PcapException("pcap_findalldevs returned failure: {}".format(
                self._ffi.string(errbuf)))
        pintf = ppintf[0]
        tmp = pintf
        pindex = 0
        while tmp != self._ffi.NULL:
            xname = self._ffi.string(
                tmp.name)  # "internal name"; still stored as bytes object
            xname = xname.decode('ascii', 'ignore')

            if self._windows:
                ext_name = "port{}".format(pindex)
            else:
                ext_name = xname
            pindex += 1

            if tmp.description == self._ffi.NULL:
                xdesc = ext_name
            else:
                xdesc = self._ffi.string(tmp.description)
                xdesc = xdesc.decode('ascii', 'ignore')

            # NB: on WinPcap, only loop flag is set
            isloop = (tmp.flags & 0x1) == 0x1
            isup = (tmp.flags & 0x2) == 0x2
            isrunning = (tmp.flags & 0x4) == 0x4
            xif = PcapInterface(ext_name, xname, xdesc, isloop, isup,
                                isrunning)
            self._interfaces.append(xif)

            tmp = tmp.next
        self._libpcap.pcap_freealldevs(pintf)

    @property
    def devices(self):
        return self._interfaces

    @property
    def lib(self):
        return self._libpcap

    @property
    def ffi(self):
        return self._ffi

    def _parse_packet(self, xdev, header, packet, nroots,
                      account_ip_padding_size):
        # MPLS header
        mpls = self._ffi.new("union mpls *")
        # IP header
        iph = self._ffi.new("struct ndpi_iphdr *")
        # IPv6 header
        iph6 = self._ffi.new("struct ndpi_ipv6hdr *")
        # lengths and offsets
        eth_offset, ether_type, wifi_len, pyld_eth_len, ip_offset, frag_off, vlan_id = 0, 0, 0, 0, 0, 0, 0
        time = (header.ts.tv_sec *
                TICK_RESOLUTION) + (header.ts.tv_usec /
                                    (1000000 / TICK_RESOLUTION))
        dlt = self._libpcap.pcap_datalink(xdev)
        datalink_check = True
        while datalink_check:
            datalink_check = False
            if header.caplen < (40 + eth_offset):
                return None  # too short
            if Dlt(dlt) == Dlt.DLT_NULL:
                tmp_dlt_null = self._ffi.cast('struct ptr_uint32 *',
                                              packet + eth_offset)
                if int(ntohs(tmp_dlt_null.value)) == 2:
                    ether_type = 0x0800
                else:
                    ether_type = 0x86dd
                ip_offset = 4 + eth_offset
            elif (Dlt(dlt) == Dlt.DLT_C_HDLC) or (
                    Dlt(dlt) == Dlt.DLT_PPP) or Dlt(dlt) == Dlt.DLT_PPP_SERIAL:
                chdlc = self._ffi.cast('struct ndpi_chdlc *',
                                       packet + eth_offset)
                ip_offset = self._ffi.sizeof('struct ndpi_chdlc')
                ether_type = ntohs(chdlc.proto_code)
            elif Dlt(dlt) == Dlt.DLT_EN10MB:  # IEEE 802.3 Ethernet - 1 */
                ethernet = self._ffi.cast('struct ndpi_ethhdr *',
                                          packet + eth_offset)
                ip_offset = self._ffi.sizeof('struct ndpi_ethhdr') + eth_offset
                check = ntohs(ethernet.h_proto)
                if check <= 1500:
                    pyld_eth_len = check
                elif check >= 1536:
                    ether_type = check
                if pyld_eth_len != 0:
                    llc = self._ffi.cast('struct ndpi_llc_header_snap *',
                                         packet + ip_offset)
                    if (llc.dsap == 0xaa) or (
                            llc.ssap
                            == 0xaa):  # check for LLC layer with SNAP ext
                        ether_type = llc.snap.proto_ID
                        ip_offset += 8
                    elif (llc.dsap == 0x42) or (llc.ssap
                                                == 0x42):  # No SNAP ext
                        return None
            elif Dlt(dlt) == Dlt.DLT_LINUX_SLL:  # Linux Cooked Capture - 113
                ether_type = (
                    packet[eth_offset + 14] << 8) + packet[eth_offset + 15]
                ip_offset = 16 + eth_offset
            elif Dlt(
                    dlt
            ) == Dlt.DLT_IEEE802_11_RADIO:  # Radiotap link-layer - 127
                radiotap = self._ffi.cast('struct ndpi_radiotap_header *',
                                          packet + eth_offset)
                radio_len = radiotap.len
                if (radiotap.flags & 0x50) == 0x50:  # Check Bad FCS presence
                    return None
                if header.caplen < (
                        eth_offset + radio_len +
                        self._ffi.sizeof('struct ndpi_wifi_header')):
                    return None
                # Calculate 802.11 header length(variable)
                wifi = self._ffi.cast('struct ndpi_wifi_header *',
                                      packet + (eth_offset + radio_len))
                fc = wifi.fc
                # Check wifi data presence
                if fcf_type(fc) == 0x2:
                    if (fcf_to_ds(fc) and fcf_from_ds(fc) == 0x0) or (
                            fcf_to_ds(fc) == 0x0 and fcf_from_ds(fc)):
                        wifi_len = 26  # + 4 byte fcs
                # Check ether_type from LLC
                llc = self._ffi.cast(
                    'struct ndpi_llc_header_snap *',
                    packet + (eth_offset + wifi_len + radio_len))
                if llc.dsap == 0xaa:
                    ether_type = ntohs(llc.snap.proto_ID)
                # Set IP header offset
                ip_offset = wifi_len + radio_len + self._ffi.sizeof(
                    'struct ndpi_llc_header_snap') + eth_offset
            elif Dlt(dlt) == Dlt.DLT_RAW:
                ip_offset, eth_offset = 0, 0
            else:
                return None

            ether_type_check = True
            while ether_type_check:
                ether_type_check = False
                if ether_type == 0x8100:
                    vlan_id = ((packet[ip_offset] << 8) +
                               packet[ip_offset + 1]) & 0xFFF
                    ether_type = (
                        packet[ip_offset + 2] << 8) + packet[ip_offset + 3]
                    ip_offset += 4
                    while ether_type == 0x8100 and self._ffi.cast(
                            'unsigned', ip_offset) < header.caplen:
                        # Double tagging for 802.1Q
                        vlan_id = ((packet[ip_offset] << 8) +
                                   packet[ip_offset + 1]) & 0xFFF
                        ether_type = (
                            packet[ip_offset + 2] << 8) + packet[ip_offset + 3]
                        ip_offset += 4
                    ether_type_check = True
                elif (ether_type == 0x8847) or (ether_type == 0x8848):
                    tmp_u32 = self._ffi.cast('struct ptr_uint32 *',
                                             packet + ip_offset)
                    mpls.u32 = int(ntohl(tmp_u32.value))
                    ether_type = 0x0800
                    ip_offset += 4
                    while not mpls.mpls.s:
                        tmp_u32_loop = self._ffi.cast('struct ptr_uint32 *',
                                                      packet + ip_offset)
                        mpls.u32 = int(ntohl(tmp_u32_loop.value))
                        ip_offset += 4
                    ether_type_check = True
                elif ether_type == 0x8864:
                    ether_type = 0x0800
                    ip_offset += 8
                    ether_type_check = True
                else:
                    pass

            ip_check = True
            while ip_check:
                ip_check = False
                if header.caplen < (ip_offset +
                                    self._ffi.sizeof('struct ndpi_iphdr')):
                    return None  # too short for next IP header
                iph = self._ffi.cast('struct ndpi_iphdr *', packet + ip_offset)
                if (ether_type == 0x0800) and (
                        header.caplen >=
                        ip_offset):  # work on Ethernet packets that contain IP
                    frag_off = ntohs(iph.frag_off)
                    if header.caplen < header.len:
                        print(
                            "WARNING: packet capture size is smaller than packet size (header.caplen < header.len)."
                        )
                if iph.version == 4:
                    ip_len = iph.ihl * 4
                    iph6 = self._ffi.NULL
                    if iph.protocol == 41:  # IPPROTO_IPV6
                        ip_offset += ip_len
                        if ip_len > 0:
                            ip_check = True
                    if (frag_off & 0x1FFF) != 0:
                        return None
                elif iph.version == 6:
                    if header.caplen < (
                            ip_offset +
                            self._ffi.sizeof('struct ndpi_ipv6hdr')):
                        return None  # too short for IPv6 header
                    iph6 = self._ffi.cast('struct ndpi_ipv6hdr *',
                                          packet + ip_offset)
                    ip_len = self._ffi.sizeof('struct ndpi_ipv6hdr')
                    if iph6.ip6_hdr.ip6_un1_nxt == 60:  # IPv6 destination option
                        options = self._ffi.cast('uint8_t *',
                                                 packet + (ip_offset + ip_len))
                        ip_len += 8 * (options[1] + 1)
                    iph = self._ffi.NULL
                else:
                    return None

        return process_packet(self._ffi, time, vlan_id, iph, iph6,
                              header.caplen - ip_offset, header.caplen, nroots,
                              account_ip_padding_size)

    def _recv_packet(self, xdev, nroots=1, account_ip_padding_size=False):
        phdr = self._ffi.new("struct pcap_pkthdr **")
        pdata = self._ffi.new("unsigned char **")
        rv = self._libpcap.pcap_next_ex(xdev, phdr, pdata)
        if rv == 1:
            return self._parse_packet(xdev, phdr[0], pdata[0], nroots,
                                      account_ip_padding_size)
        elif rv == 0:  # timeout; nothing to return
            return 0
        elif rv == -1:  # error on receive; raise an exception
            s = self._ffi.string(self._libpcap.pcap_geterr(xdev))
            raise PcapException("Error receiving packet: {}".format(s))
        elif rv == -2:  # reading from savefile, but none left
            return -2
示例#55
0
def build():
    ffi = FFI()

    for file in ["libnek5000.h"]:
        with open(file) as header:
            func_prototypes = header.read()
            ffi.cdef(func_prototypes)

    MPI = False

    # os.environ["LD_LIBRARY_PATH"] = os.getcwd()

    source = """
#include "libnek5000.h"
"""
    if MPI:
        #  source = '#include "mpi.h"' + source
        ffi.cdef("#define MPI_COMM_WORLD ...")

    # import subprocess
    # ompi_ldflags = subprocess.getoutput("pkg-config --libs ompi").split()
    #  extra_link_args=ompi_ldflags
    # ['-Wl,-rpath=.', '-L$PWD']
    if MPI:
        ffi.set_source_pkgconfig(
            "nek5000_ffi",
            pkgconfig_libs=["ompi"],
            source=source,
            libraries=["nek5000"],
        )
    else:
        ffi.set_source(
            "nek5000_ffi",
            source=source,
            libraries=["nek5000"],
        )

    lib = ffi.compile(verbose=True)

    return lib, ffi
示例#56
0
import sys
import numpy
import _convert

from cffi import FFI

ffi = FFI()

# window size 2
# RGB array (3D)

my_input = numpy.array([
    [[1, 2, 3], [5, 6, 7], [4, 5, 6], [6, 4, 5]],
    [[4, 6, 3], [5, 8, 7], [6, 3, 6], [5, 8, 5]],
    [[3, 7, 3], [4, 5, 7], [5, 2, 5], [4, 5, 5]],
    [[2, 8, 3], [3, 2, 7], [1, 2, 6], [3, 1, 5]],
],
                       dtype=numpy.float32)

window_size = 2
sample_count = 3 * (my_input.shape[0] - window_size + 1) * (my_input.shape[1] -
                                                            window_size + 1)
print('window_size -> ' + str(window_size) + ' ... sample_count -> ' +
      str(sample_count))
my_output = numpy.zeros((sample_count, window_size, window_size),
                        dtype=numpy.float32)

_x = _convert.ffi.cast('size_t', my_input.shape[0])
_y = _convert.ffi.cast('size_t', my_input.shape[1])
_window_size = _convert.ffi.cast('size_t', window_size)
_my_input = _convert.ffi.cast('float *', my_input.ctypes.data)
示例#57
0
    LOGISTIC = 0
    RELU = 1
    RELIE = 2
    LINEAR = 3
    RAMP = 4
    TANH = 5
    PLSE = 6
    LEAKY = 7
    ELU = 8
    LOGGY = 9
    STAIR = 10
    HARDTAN = 11
    LHTAN = 12


__darknetffi__ = FFI()

__darknetffi__.cdef("""
typedef struct network network;
typedef struct layer layer;

typedef struct{
    int *leaf;
    int n;
    int *parent;
    int *child;
    int *group;
    char **name;

    int groups;
    int *group_size;
示例#58
0
#!/usr/bin/env python

from future import standard_library
standard_library.install_aliases()

from subprocess import getstatusoutput
from cffi import FFI

ffi = FFI()

SS_ALIGNTYPE = "unsigned long"
SS_PADSIZE = 128 - 2 - ffi.sizeof(SS_ALIGNTYPE)
IN_PORT_T = "unsigned short int"
SIN_PADSIZE = 16 - ffi.sizeof(IN_PORT_T) - ffi.sizeof("unsigned short int") - 4

nim_prefix = """/* auto generated */

#ifdef C2NIM
#  dynlib libzerotiercore
#  cdecl
#  if defined(windows)
#    define libzerotiercore "zerotiercore.dll"
#  elif defined(macosx)
#    define libzerotiercore "libzerotiercore.dylib"
#  else
#    define libzerotiercore "libzerotiercore.so"
#  endif
#endif

#include <stdint.h>
示例#59
0
from cffi import FFI
ffibuilder = FFI()
ffibuilder.cdef("int addme(int a, int b);")
ffibuilder.set_source("pyadd", '#include "add.h"', sources=["add.c"])
ffibuilder.compile()
示例#60
0

def system_bits():
    return struct.calcsize('P') * 8


def st_nlink_type():
    if sys.platform == "darwin" or sys.platform.startswith("freebsd"):
        return "short"
    if system_bits() == 32:
        return "unsigned long"
    return "long long"


from cffi import FFI
ffi = FFI()

thisdir = os.path.dirname(os.path.abspath(__file__))


def read_source(name):
    with open(os.path.join(thisdir, name), 'r') as f:
        return f.read()


_cdef = read_source('_corecffi_cdef.c')
_source = read_source('_corecffi_source.c')

_cdef = _cdef.replace('#define GEVENT_ST_NLINK_T int', '')
_cdef = _cdef.replace('#define GEVENT_STRUCT_DONE int', '')
_cdef = _cdef.replace('#define GEVENT_UV_OS_SOCK_T int', '')