Compile fortran module with f2py and Python 3.6 on Windows 10

I had the same issue. The top answer helps a lot. I would like to add some comments about the missing DLLs. A useful tool to help you find out which DLLs are missing is Process Monitor. You only need to add a filter python.exe and track which DLLs are failed to load. For me, the following ones are missing:

  • libgcc_s_seh-1.dll
  • libgfortran-5.dll
  • libquadmath-0.dll
  • libwinpthread-1.dll

I just need to copy them from the bin/ directory of my MinGW toolchain to the same directory of python.exe


Finally got this working.

Short version:

Make sure you use 64-bit compilers (triple check the build for mingw-w64) for 64-bit Python. Not as obvious as it sounds to an f2py newb on Windows.

Long version:

I uninstalled my existing copy of MinGW (I suspect it was a 32 bit version) and instead downloaded a specific 64-bit build of mingw-w64 7.2.0 from sourceforge, specifically x86_64-7.2.0-release-posix-seh-rt_v5-rev1.7z. This stackoverflow question was useful.

I unzipped and copied the "mingw64" folder into my C: drive (C:\mingw64). I added C:\mingw64\bin to my user Path.

I uninstalled the anaconda version of MinGW with conda uninstall mingw. Note, this is only necessary if you've previously installed MinGW using conda.

Upon running f2py -c igrf12.pyf igrf12.f --compiler=mingw32 (in same directory as igrf12.pyf, see Scipy Documentation for how to generate *.pyf file), pyigrf12.cp36-win_amd64.pyd is created without any errors. I can finally import pyigrf12 successfully and access the underlying Fortran subroutines (e.g. igrf12syn).

Note, I can also run f2py -c igrf12.pyf igrf12.f --compiler=msvc successfully, but then I have to manually copy and paste the libigrf12....gfortran-win_amd64.dll (generated in .\UNKNOWN\.libs\) into the same directory as pyigrf12.cp36-win_amd64.pyd to avoid ImportError: DLL load failed: The specified module could not be found. mentioned in Method 2 of my question.

Just to re-iterate: Make sure C:\mingw64\bin is added to your path!

By the way, f2py was painless for me on macOS Sierra and Ubuntu. If the above still doesn't work for you, I recommend trying on Linux, macOS or Windows Subsystem for Linux.