使用f2py编译Fortran代码后导入遇DLL加载失败错误求助
Fortran模块通过f2py编译后导入失败问题
问题代码
以下是我编写的Fortran模块代码:
module date_mod implicit none private public :: Date type :: Date integer :: year integer :: month integer :: day contains procedure :: init procedure :: shift_by_months procedure :: print_date end type Date contains subroutine init(self, y, m, d) class(Date), intent(out) :: self integer, intent(in) :: y, m, d self%year = y self%month = m self%day = d end subroutine init end module date_mod
编译命令
我使用f2py编译该代码的命令:
f2py -c -m date date.f90
导入错误
在Python中导入模块时出现如下错误:
ImportError Traceback (most recent call last) Cell In[1], line 1 ----> 1 import date 3 # Create and use Date object 4 date_obj = date.Date() ImportError: DLL load failed while importing date: 找不到指定的模块。
我尝试过多种编译器组合,但问题仍未解决。
解决方法
针对这个DLL加载失败的问题,可以尝试以下步骤:
- 配置编译器环境变量:确保所用Fortran编译器(如gfortran)的bin目录已添加到系统PATH中。Windows系统下,编译生成的模块依赖编译器的运行时库,必须保证这些库能被系统检索到。
- 显式指定编译器:在f2py命令中明确指定编译器,例如使用GNU Fortran:
f2py -c -m date date.f90 --fcompiler=gnu95 - 检查编译过程输出:执行编译命令时,留意是否有警告或错误信息,确认编译全程无异常完成,没有依赖缺失。
- 利用conda管理环境:如果使用conda环境,先安装Fortran编译器:
之后在激活的conda环境中重新执行f2py编译命令,conda会自动管理所需的依赖库。conda install -c conda-forge gfortran - 避免模块名冲突:Python标准库本身包含
date模块,建议修改编译生成的模块名称(比如改为date_mod),避免命名冲突:
导入时使用f2py -c -m date_mod date.f90import date_mod即可。
内容的提问来源于stack exchange,提问作者Victor Schweppe
相关产品推荐
相关产品推荐

