[pypy-commit] cffi default: hg merge demo-cleanup

arigo pypy.commits at gmail.com
Thu Jan 7 10:56:03 EST 2016


Author: Armin Rigo <arigo at tunes.org>
Branch: 
Changeset: r2546:89e4262a2073
Date: 2016-01-07 16:55 +0100
http://bitbucket.org/cffi/cffi/changeset/89e4262a2073/

Log:	hg merge demo-cleanup

	Thanks Matti :-)

diff --git a/demo/btrfs-snap.py b/demo/btrfs-snap.py
--- a/demo/btrfs-snap.py
+++ b/demo/btrfs-snap.py
@@ -22,10 +22,14 @@
     };
 """)
 
-v = ffi.verify("#include <btrfs/ioctl.h>")
+ffi.set_source("_btrfs_cffi", "#include <btrfs/ioctl.h>")
+ffi.compile()
 
+# ____________________________________________________________
 
 
+from _btrfs_cffi import ffi, lib
+
 parser = argparse.ArgumentParser(usage=__doc__.strip())
 parser.add_argument('source', help='source subvolume')
 parser.add_argument('target', help='target directory')
@@ -41,7 +45,7 @@
 args.fd = source
 args_buffer = ffi.buffer(args)
 try:
-    fcntl.ioctl(target, v.BTRFS_IOC_SNAP_CREATE_V2, args_buffer)
+    fcntl.ioctl(target, lib.BTRFS_IOC_SNAP_CREATE_V2, args_buffer)
 except IOError as e:
     print e
     sys.exit(1)
diff --git a/demo/fastcsv.py b/demo/fastcsv.py
--- a/demo/fastcsv.py
+++ b/demo/fastcsv.py
@@ -4,9 +4,8 @@
 # IN-PROGRESS.  See the demo at the end of the file
 
 
-dialect2ffi = {}
-
-def _make_ffi_from_dialect(dialect):
+def _make_ffi_from_dialect(dialect_name):
+    dialect = csv.get_dialect(dialect_name)
 
     ffi = cffi.FFI()
 
@@ -26,7 +25,7 @@
     else:
         d['is_escape_char'] = '&& 0'
 
-    lib = ffi.verify(r'''
+    ffi.set_source('_fastcsv_' + dialect_name, r'''
 
     typedef enum {
         START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
@@ -237,15 +236,16 @@
     }
     ''' % d)
 
-    return ffi, lib
+    ffi.compile()
 
 
-def fastcsv_reader(f, dialect):
-    dialect = csv.get_dialect(dialect)
+def fastcsv_reader(f, dialect_name):
     try:
-        ffi, lib = dialect2ffi[dialect]
-    except KeyError:
-        ffi, lib = dialect2ffi[dialect] = _make_ffi_from_dialect(dialect)
+        module = __import__('_fastcsv_' + dialect_name)
+    except ImportError:
+        _make_ffi_from_dialect(dialect_name)
+        module = __import__('_fastcsv_' + dialect_name)
+    ffi, lib = module.ffi, module.lib
     #
     linelen = -1
     for line in f:
diff --git a/demo/gmp.py b/demo/gmp.py
--- a/demo/gmp.py
+++ b/demo/gmp.py
@@ -1,33 +1,30 @@
 import sys
-import cffi
-
 #
 # This is only a demo based on the GMP library.
-# There is a rather more complete version available at:
+# There is a rather more complete (but perhaps outdated) version available at:
 # http://bazaar.launchpad.net/~tolot-solar-empire/+junk/gmpy_cffi/files
 #
 
-ffi = cffi.FFI()
+try:
+    from _gmp_cffi import ffi, lib
+except ImportError:
+    print 'run gmp_build first, then make sure the shared object is on sys.path'
+    sys.exit(1)
 
-ffi.cdef("""
-
-    typedef struct { ...; } MP_INT;
-    typedef MP_INT mpz_t[1];
-
-    int mpz_init_set_str (MP_INT *dest_integer, char *src_cstring, int base);
-    void mpz_add (MP_INT *sum, MP_INT *addend1, MP_INT *addend2);
-    char * mpz_get_str (char *string, int base, MP_INT *integer);
-
-""")
-
-lib = ffi.verify("#include <gmp.h>",
-                 libraries=['gmp', 'm'])
+# ffi "knows" about the declared variables and functions from the
+#     cdef parts of the module created from gmp_build
+# lib "knows" how to call the functions from the set_source parts
+#     of the module.
 
 # ____________________________________________________________
 
 a = ffi.new("mpz_t")
 b = ffi.new("mpz_t")
 
+if len(sys.argv) < 3:
+    print 'call as %s bigint1, bigint2' % sys.argv[0]
+    sys.exit(2)
+
 lib.mpz_init_set_str(a, sys.argv[1], 10)	# Assume decimal integers
 lib.mpz_init_set_str(b, sys.argv[2], 10)	# Assume decimal integers
 lib.mpz_add(a, a, b)			# a=a+b
diff --git a/demo/gmp_build.py b/demo/gmp_build.py
new file mode 100644
--- /dev/null
+++ b/demo/gmp_build.py
@@ -0,0 +1,27 @@
+import cffi
+
+#
+# This is only a demo based on the GMP library.
+# There is a rather more complete (but perhaps outdated) version available at:
+# http://bazaar.launchpad.net/~tolot-solar-empire/+junk/gmpy_cffi/files
+#
+
+ffi = cffi.FFI()
+
+ffi.cdef("""
+
+    typedef struct { ...; } MP_INT;
+    typedef MP_INT mpz_t[1];
+
+    int mpz_init_set_str (MP_INT *dest_integer, char *src_cstring, int base);
+    void mpz_add (MP_INT *sum, MP_INT *addend1, MP_INT *addend2);
+    char * mpz_get_str (char *string, int base, MP_INT *integer);
+
+""")
+
+ffi.set_source('_gmp_cffi', "#include <gmp.h>",
+                 libraries=['gmp', 'm'])
+
+if __name__ == '__main__':
+    ffi.compile()
+
diff --git a/demo/pwuid.py b/demo/pwuid.py
--- a/demo/pwuid.py
+++ b/demo/pwuid.py
@@ -1,14 +1,7 @@
-from cffi import FFI
-ffi = FFI()
-ffi.cdef("""     // some declarations from the man page
-    struct passwd {
-        char *pw_name;
-        ...; 
-    };
-    struct passwd *getpwuid(int uid);
-""")
-C = ffi.verify("""   // passed to the real C compiler
-#include <sys/types.h>
-#include <pwd.h>
-""")
-print ffi.string(C.getpwuid(0).pw_name)
+import sys, os
+
+# run pwuid_build first, then make sure the shared object is on sys.path
+from _pwuid_cffi import ffi, lib
+
+
+print ffi.string(lib.getpwuid(0).pw_name)
diff --git a/demo/pwuid_build.py b/demo/pwuid_build.py
new file mode 100644
--- /dev/null
+++ b/demo/pwuid_build.py
@@ -0,0 +1,18 @@
+from cffi import FFI
+ffi = FFI()
+ffi.cdef("""     // some declarations from the man page
+    struct passwd {
+        char *pw_name;
+        ...; 
+    };
+    struct passwd *getpwuid(int uid);
+""")
+
+ffi.set_source('_pwuid_cffi', """   // passed to the real C compiler
+#include <sys/types.h>
+#include <pwd.h>
+""")
+
+
+if __name__ == '__main__':
+    ffi.compile()
diff --git a/demo/readdir2.py b/demo/readdir2.py
--- a/demo/readdir2.py
+++ b/demo/readdir2.py
@@ -1,11 +1,13 @@
-# A Linux-only demo, using verify() instead of hard-coding the exact layouts
+# A Linux-only demo, using set_source() instead of hard-coding the exact layouts
 #
 import sys
-from _readdir2 import ffi, lib
 
 if not sys.platform.startswith('linux'):
     raise Exception("Linux-only demo")
 
+# run readdir2_build first, then make sure the shared object is on sys.path
+from _readdir2_cffi import ffi, lib
+
 
 def walk(basefd, path):
     print '{', path
diff --git a/demo/readdir2_build.py b/demo/readdir2_build.py
--- a/demo/readdir2_build.py
+++ b/demo/readdir2_build.py
@@ -20,7 +20,7 @@
     static const int DT_DIR;
 
 """)
-ffi.set_source("_readdir2", """
+ffi.set_source("_readdir2_cffi", """
 #ifndef _ATFILE_SOURCE
 #  define _ATFILE_SOURCE
 #endif
diff --git a/demo/winclipboard.py b/demo/winclipboard.py
--- a/demo/winclipboard.py
+++ b/demo/winclipboard.py
@@ -1,60 +1,40 @@
 __author__ = "Israel Fruchter <israel.fruchter at gmail.com>"
 
-from cffi import FFI
+import sys, os
 
-ffi = FFI()
-ffi.cdef('''
-    typedef void * HANDLE;
-    typedef HANDLE HWND;
-    typedef int BOOL;
-    typedef unsigned int UINT;
-    typedef int SIZE_T;
-    typedef char * LPTSTR;
-    typedef HANDLE HGLOBAL;
-    typedef HANDLE LPVOID;
+if not sys.platform == 'win32':
+    raise Exception("Windows-only demo")
 
-    HWND GetConsoleWindow(void);
+try:
+    from _winclipboard_cffi import ffi, lib
+except ImportError:
+    print 'run winclipboard_build first, then make sure the shared object is on sys.path'
+    sys.exit(1)
 
-    LPVOID GlobalLock( HGLOBAL hMem );
-    BOOL GlobalUnlock( HGLOBAL hMem );
-    HGLOBAL GlobalAlloc(UINT uFlags, SIZE_T dwBytes);
-
-    BOOL  OpenClipboard(HWND hWndNewOwner);
-    BOOL  CloseClipboard(void);
-    BOOL  EmptyClipboard(void);
-    HANDLE  SetClipboardData(UINT uFormat, HANDLE hMem);
-
-    #define CF_TEXT ...
-    #define GMEM_MOVEABLE ...
-
-    void * memcpy(void * s1, void * s2, int n);
-    ''')
-
-lib = ffi.verify('''
-    #include <windows.h>
-''', libraries=["user32"])
-
-globals().update(lib.__dict__)
+# ffi "knows" about the declared variables and functions from the
+#     cdef parts of the module _winclipboard_cffi created,
+# lib "knows" how to call the functions from the set_source parts
+#     of the module.
 
 def CopyToClipboard(string):
     '''
         use win32 api to copy `string` to the clipboard
     '''
-    hWnd = GetConsoleWindow()
+    hWnd = lib.GetConsoleWindow()
   
-    if OpenClipboard(hWnd):
+    if lib.OpenClipboard(hWnd):
         cstring = ffi.new("char[]", string)
         size = ffi.sizeof(cstring)
         
         # make it a moveable memory for other processes
-        hGlobal = GlobalAlloc(GMEM_MOVEABLE, size)
-        buffer = GlobalLock(hGlobal)
-        memcpy(buffer, cstring, size)
-        GlobalUnlock(hGlobal)
+        hGlobal = lib.GlobalAlloc(lib.GMEM_MOVEABLE, size)
+        buffer = lib.GlobalLock(hGlobal)
+        lib.memcpy(buffer, cstring, size)
+        lib.GlobalUnlock(hGlobal)
         
-        res = EmptyClipboard()
-        res = SetClipboardData(CF_TEXT, buffer)
+        res = lib.EmptyClipboard()
+        res = lib.SetClipboardData(lib.CF_TEXT, buffer)
  
-        CloseClipboard()
+        lib.CloseClipboard()
         
 CopyToClipboard("hello world from cffi")
diff --git a/demo/winclipboard_build.py b/demo/winclipboard_build.py
new file mode 100644
--- /dev/null
+++ b/demo/winclipboard_build.py
@@ -0,0 +1,36 @@
+from cffi import FFI
+
+ffi = FFI()
+ffi.cdef('''
+    typedef void * HANDLE;
+    typedef HANDLE HWND;
+    typedef int BOOL;
+    typedef unsigned int UINT;
+    typedef int SIZE_T;
+    typedef char * LPTSTR;
+    typedef HANDLE HGLOBAL;
+    typedef HANDLE LPVOID;
+
+    HWND GetConsoleWindow(void);
+
+    LPVOID GlobalLock( HGLOBAL hMem );
+    BOOL GlobalUnlock( HGLOBAL hMem );
+    HGLOBAL GlobalAlloc(UINT uFlags, SIZE_T dwBytes);
+
+    BOOL  OpenClipboard(HWND hWndNewOwner);
+    BOOL  CloseClipboard(void);
+    BOOL  EmptyClipboard(void);
+    HANDLE  SetClipboardData(UINT uFormat, HANDLE hMem);
+
+    #define CF_TEXT ...
+    #define GMEM_MOVEABLE ...
+
+    void * memcpy(void * s1, void * s2, int n);
+    ''')
+
+ffi.set_source('_winclipboard_cffi', '''
+    #include <windows.h>
+''', libraries=["user32"])
+
+if __name__ == '__main__':
+    ffi.compile()
diff --git a/demo/xclient.py b/demo/xclient.py
--- a/demo/xclient.py
+++ b/demo/xclient.py
@@ -1,40 +1,27 @@
-from cffi import FFI
+import sys, os
 
-ffi = FFI()
-ffi.cdef("""
+# run xclient_build first, then make sure the shared object is on sys.path
+from _xclient_cffi import ffi, lib
 
-typedef ... Display;
-typedef struct { ...; } Window;
 
-typedef struct { int type; ...; } XEvent;
+# ffi "knows" about the declared variables and functions from the
+#     cdef parts of the module xclient_build created,
+# lib "knows" how to call the functions from the set_source parts
+#     of the module.
 
-Display *XOpenDisplay(char *display_name);
-Window DefaultRootWindow(Display *display);
-int XMapRaised(Display *display, Window w);
-Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
-                           unsigned int width, unsigned int height,
-                           unsigned int border_width, unsigned long border,
-                           unsigned long background);
-int XNextEvent(Display *display, XEvent *event_return);
-""")
-lib = ffi.verify("""
-#include <X11/Xlib.h>
-""", libraries=['X11'])
-
-globals().update(lib.__dict__)
 
 class XError(Exception):
     pass
 
 def main():
-    display = XOpenDisplay(ffi.NULL)
+    display = lib.XOpenDisplay(ffi.NULL)
     if display == ffi.NULL:
         raise XError("cannot open display")
-    w = XCreateSimpleWindow(display, DefaultRootWindow(display),
+    w = lib.XCreateSimpleWindow(display, lib.DefaultRootWindow(display),
                             10, 10, 500, 350, 0, 0, 0)
-    XMapRaised(display, w)
+    lib.XMapRaised(display, w)
     event = ffi.new("XEvent *")
-    XNextEvent(display, event)
+    lib.XNextEvent(display, event)
 
 if __name__ == '__main__':
     main()
diff --git a/demo/xclient_build.py b/demo/xclient_build.py
new file mode 100644
--- /dev/null
+++ b/demo/xclient_build.py
@@ -0,0 +1,25 @@
+from cffi import FFI
+ffi = FFI()
+ffi.cdef("""
+
+typedef ... Display;
+typedef struct { ...; } Window;
+
+typedef struct { int type; ...; } XEvent;
+
+Display *XOpenDisplay(char *display_name);
+Window DefaultRootWindow(Display *display);
+int XMapRaised(Display *display, Window w);
+Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
+                           unsigned int width, unsigned int height,
+                           unsigned int border_width, unsigned long border,
+                           unsigned long background);
+int XNextEvent(Display *display, XEvent *event_return);
+""")
+
+ffi.set_source('_xclient_cffi', """
+            #include <X11/Xlib.h>
+""", libraries=['X11'])
+
+if __name__ == '__main__':
+    ffi.compile()


More information about the pypy-commit mailing list