• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import cffi
2
3ffi = cffi.FFI()
4
5ffi.cdef("""
6    int my_algo(int);
7    typedef ... va_list;
8    extern "Python" int f(int, va_list *);
9
10    int fetch_int(va_list *);
11    double fetch_double(va_list *);
12    void *fetch_ptr(va_list *);
13""")
14
15ffi.set_source("_extern_python_cffi", """
16    #include <stdarg.h>
17
18    static int f(int, va_list *);
19
20    static int f1(int n, ...)
21    {
22        va_list ap;
23        va_start(ap, n);
24        int res = f(n, &ap);
25        va_end(ap);
26        return res;
27    }
28
29    static int fetch_int(va_list *va) { return va_arg((*va), int); }
30    static double fetch_double(va_list *va) { return va_arg((*va), double); }
31    static void * fetch_ptr(va_list *va) { return va_arg((*va), void *); }
32
33    static int my_algo(int n) {
34        return f1(3, n, n+1, n+2) + f1(1, &n) + f1(2, 12.3, 45.6);
35    }
36""")
37
38ffi.compile()
39
40
41from _extern_python_cffi import ffi, lib
42
43@ffi.def_extern()
44def f(n, va):
45    if n == 3:
46        x = lib.fetch_int(va)
47        y = lib.fetch_int(va)
48        z = lib.fetch_int(va)
49        print (x, y, z)
50    elif n == 1:
51        ptr = lib.fetch_ptr(va)
52        print 'ptr to:', ffi.cast("int *", ptr)[0]
53    elif n == 2:
54        x = lib.fetch_double(va)
55        y = lib.fetch_double(va)
56        print (x, y)
57    else:
58        raise AssertionError(n)
59    return 14
60
61print lib.my_algo(10)
62