如何通过f2py仅将单个Fortran库函数暴露给Python接口
使用f2py仅为指定Fortran函数生成Python接口
要解决f2py解析整个代码库报错的问题,核心是通过**接口定义文件(.pyf)**明确指定仅为run(n)生成Python接口,跳过对其他函数的解析。以下是具体步骤:
1. 编写接口定义文件
创建一个名为my_interface.pyf的文件,内容根据run是子例程还是函数调整:
情况1:run是子例程(无返回值)
! my_interface.pyf python module myfortran interface subroutine run(n) integer, intent(in) :: n ! 声明输入参数n为整数类型 end subroutine run end interface end python module myfortran
情况2:run是函数(有整数返回值)
! my_interface.pyf python module myfortran interface integer function run(n) integer, intent(in) :: n end function run end interface end python module myfortran
这个文件会告诉f2py:只需要为run生成接口,无需处理代码库中的其他内容。
2. 执行编译命令
在终端运行以下命令,编译接口文件和所有run依赖的Fortran源文件(如果源文件分散在不同目录,可替换为具体路径,比如src/*.f):
f2py -c my_interface.pyf *.f
编译完成后,会生成myfortran.so(Linux/macOS)或myfortran.pyd(Windows)格式的Python扩展模块。
3. 在Python中调用
直接导入生成的模块即可调用run函数:
import myfortran myfortran.run(10) # 传入整数参数,示例值为10
注意事项
- 必须将
run内部调用的所有Fortran源文件包含在编译命令中,否则会出现链接错误。如果不确定依赖范围,可直接传入所有.f文件(*.f)。 - 原代码库中名称含空格、类型不规范的函数不会被f2py解析,因为我们通过pyf文件限定了仅处理
run,因此不会触发相关报错。
内容的提问来源于stack exchange,提问作者iamhiding
相关产品推荐
相关产品推荐

