0

I was learning how to integrate gmpy2 with Cython. From the docs, I was provided with an example code. Since I am not really sure about what was going on, I felt that I can learn how to use gmpy in Cython by playing with the example code provided.

The example code:
setup.py

   "A minimal setup.py for compiling test_gmpy2.pyx"
    
    from distutils.core import setup
    from distutils.extension import Extension
    from Cython.Build import cythonize
    import sys
    
    ext = Extension("test_gmpy2", ["test_gmpy2.pyx"], include_dirs=sys.path, libraries=['gmp', 'mpfr', 'mpc'])
    
    setup(
        name="cython_gmpy_test",
        ext_modules=cythonize([ext], include_path=sys.path)
    )

test_gmpy2.pyx

    "A minimal cython file test_gmpy2.pyx"

    from gmpy2 cimport *
    
    cdef extern from "gmp.h":
        void mpz_set_si(mpz_t, long)
    
    import_gmpy2()   # needed to initialize the C-API
    
    cdef mpz z = GMPy_MPZ_New(NULL)
    mpz_set_si(MPZ(z), -7)
    
    print(z + 3)

Running setup.py gives me this error:

fatal error C1083: Cannot open include file: 'gmp.h': No such file or directory

What is wrong? How do I fix it? I checked my install for gmpy. I believe there isn't anything wrong with it.

chdy
  • 11
  • 3
  • Is `gmp.h` in the same directory as the file? – 12944qwerty Dec 21 '21 at 02:24
  • 1
    I maintain gmpy2. If you are on Linux, you'll need to install the development headers for GMP, MPFR, and MPC. `sudo apt install libmpc-dev` or similar will do that. If you are using Windows, let me know. – casevh Dec 21 '21 at 02:28
  • Hello! gmp.h is not in the same directory as the file, and I am using windows. – chdy Dec 21 '21 at 03:13
  • Good news: I'm able to successfully build the Cython test suite on Windows. Bad news: I haven't properly documented it. I've created https://github.com/aleaxit/gmpy/issues/320 to document the procedure. If you can help test / provide feedback, please leave a comment there. Once it is working, I leave a complete answer. – casevh Dec 21 '21 at 05:49

1 Answers1

1

I can provide a working example. The package fractalshades includes a Cython extension which imports (cimport) gmpy2 and is compiled both under Linux and Windows.

The code for the Cython extension is hosted here https://github.com/GBillotey/Fractalshades/blob/master/src/fractalshades/mpmath_utils/FP_loop.pyx

The key parts to compile for windows (with MS Visual Studio) have been :

  • includes the headers in gmpy2 installation directory
  • An import library (.lib file) is necessary when calling functions in a dll - it provides the stubs that hook up to the DLL at runtime. To generate these .lib one can use dumpbin & lib executables provided by visual studio.

For implementation details, the Windows build is run on a github runner with the full script available as a Github workflow.

GBy
  • 1,719
  • 13
  • 19