欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Windows下利用gfortran编译dll供python调用

程序员文章站 2022-07-14 15:41:04
...
运行环境
系统 Windows10
Python Python3.7.0 64位
编译工具 gfortran
Fortran编译环境 minGW64
问题描述

需要在python项目中调用别人写好的Fortran代码,Fortran代码版本较杂,f77 f90 f95同时共存。

解决方案

目前有两种解决方案,目前针对于简单代码均可以成功运行,但针对复杂代码在编译时就会报错,后续解决问题后再来补充,目前先贴出来解决方案供参考:

  1. 利用f2py将Fortran代码编译为pyd格式,在python中将Fortran代码可以作为模块进行调用
  2. 利用gfortran或intel的编译工具,将Fortran代码编译为dll文件,在python中借用ctypes进行加载并调用
示例代码

hello_subroutine.f90

subroutine hello
    print *,'hello world'
end subroutine hello

hello_program.f90

program main
  implicit none
  print *, 'Hello World'
end program main
方案一:F2Py

具体信息见官网:F2PY - Calling Fortran routines from Python
编译方式:
python2下:
python -m numpy.f2py -c hello_subroutine.f90 -m hello_subroutine 建议这种方式
f2py -c hello_subroutine.f90 -m hello_subroutine
python3下
python3 -m numpy.f2py -c hello_subroutine.f90 -m hello_subroutine 建议这种方式
f2py3 -c hello_subroutine.f90 -m hello_subroutine
编译后会生成hello_subroutine.pyd文件
调用方式:

from hello_subroutine import hello  # 需注意路径问题
print(hello())
方案二:gfortran

首先需自行配置minGW64,网上资料较多,按照说明配置好环境变量,在dos窗口中输入gfortran --version能够输出其版本信息则说明安装成功。

  1. 生成exe文件:
    gfortran -o hello_program hello_program.f90
    运行:./hello_program.exe
    需要注意的是,若用这种方式编译hello_subroutine.f90,则会报错
D:/software/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status
  1. 生成dll文件:
  1. gfortran -shared -fPIC -o hello_subroutine.dll hello_subroutine.f90 —— 编译后,引用其中函数时,需在函数名称后添加_,eq:hello_
  2. gfortran -shared -fPIC -g -o hello_subroutine.dll hello_subroutine.f90 -fno-underscoring —— 可直接引用原函数名
    调用方式:
from ctypes import cdll, windll, CDLL, WinDLL
dllpath = 'hello_subroutine.dll'
dll1 = cdll.LoadLibrary(dllpath)  # cdll是CDLL类的对象
dll2 = windll.LoadLibrary(dllpath)  # windll是WinDLL类的对象
dll3 = CDLL(dllpath)
dll4 = WinDLL(dllpath)
dll1.hello_()  # 针对于方式1)
dll1.hello()  # 针对于方式2)

遇到的问题:

  1. D:/software/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain' collect2.exe: error: ld returned 1 exit status
    已在上面说明
  2. OSError: exception: access violation reading 0x0000000000007530
    暂未解决,待补充。

参考文献:
[1] F2PY - Calling Fortran routines from Python
[2] call functions from a shared fortran library in python
[3] creating DLL with gfortran on Windows
[4] …


以上,欢迎补充&交流。