gmp.py 929 B

123456789101112131415161718192021222324252627282930313233343536
  1. import sys
  2. import cffi
  3. #
  4. # This is only a demo based on the GMP library.
  5. # There is a rather more complete version available at:
  6. # http://bazaar.launchpad.net/~tolot-solar-empire/+junk/gmpy_cffi/files
  7. #
  8. ffi = cffi.FFI()
  9. ffi.cdef("""
  10. typedef struct { ...; } MP_INT;
  11. typedef MP_INT mpz_t[1];
  12. int mpz_init_set_str (MP_INT *dest_integer, char *src_cstring, int base);
  13. void mpz_add (MP_INT *sum, MP_INT *addend1, MP_INT *addend2);
  14. char * mpz_get_str (char *string, int base, MP_INT *integer);
  15. """)
  16. lib = ffi.verify("#include <gmp.h>",
  17. libraries=['gmp', 'm'])
  18. # ____________________________________________________________
  19. a = ffi.new("mpz_t")
  20. b = ffi.new("mpz_t")
  21. lib.mpz_init_set_str(a, sys.argv[1], 10) # Assume decimal integers
  22. lib.mpz_init_set_str(b, sys.argv[2], 10) # Assume decimal integers
  23. lib.mpz_add(a, a, b) # a=a+b
  24. s = lib.mpz_get_str(ffi.NULL, 10, a)
  25. print ffi.string(s)