|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import sys |
| 4 | + |
| 5 | +lib_ext = ('.so' if ('darwin' in sys.platform or |
| 6 | + 'linux' in sys.platform) |
| 7 | + else ".dll") |
| 8 | + |
| 9 | +import ctypes |
| 10 | + |
| 11 | +# now load our own shared library |
| 12 | +add = ctypes.cdll.LoadLibrary("add"+lib_ext) |
| 13 | + |
| 14 | +print "This should be 7:", |
| 15 | +print add.add(3,4) |
| 16 | + |
| 17 | +# Using an already-loaded shared library: |
| 18 | +## loading libc and libm (math) |
| 19 | +if 'darwin' in sys.platform: |
| 20 | + # OS-X likes full paths... |
| 21 | + libc = ctypes.CDLL("/usr/lib/libc.dylib") |
| 22 | + libm = ctypes.CDLL("/usr/lib/libm.dylib") |
| 23 | +elif 'linux' in sys.platform: |
| 24 | + # linux uses the shared lib search path |
| 25 | + libc = ctypes.CDLL("libc.so") |
| 26 | + libm = ctypes.CDLL("libm.so") |
| 27 | +elif 'win' in sys.platform: |
| 28 | + # Windows can find already loaded dlls by name |
| 29 | + libc = ctypes.cdll.msvcrt # lib c and libm are in msvcrt |
| 30 | + libm = ctypes.cdll.msvcrt |
| 31 | + |
| 32 | +libc.printf("printed via libc printf()\n") |
| 33 | + |
| 34 | +print "passing different types to printf:" |
| 35 | +#libc.printf("An int %d, a double %f\n", 1234, 3.14) |
| 36 | +libc.printf("An int %d, a double %f\n", 1234, ctypes.c_double(3.14)) |
| 37 | + |
| 38 | + |
| 39 | +## Calling libm |
| 40 | +## prototype for pow(): |
| 41 | +## double pow ( double x, double y ) |
| 42 | + |
| 43 | +print "This should be 81.0:", |
| 44 | +print libm.pow(ctypes.c_double(3), ctypes.c_double(4)) |
| 45 | + |
| 46 | +## need to set the return type! |
| 47 | +libm.pow.restype = ctypes.c_double |
| 48 | +print "This should be 81.0:", |
| 49 | +print libm.pow(ctypes.c_double(3), ctypes.c_double(4)) |
| 50 | + |
| 51 | +## if you are going to call the same function a lot, |
| 52 | +## you can specify the arument types: |
| 53 | + |
| 54 | +libm.pow.restype = ctypes.c_double |
| 55 | +libm.pow.argtypes = [ctypes.c_double, ctypes.c_double] |
| 56 | +print "This should be 81.0:", |
| 57 | +print libm.pow(3, 4.0) |
| 58 | + |
| 59 | +## much easier! |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + |
0 commit comments