使用SWIG从Fortran源代码创建Python模块

Creating a Python module from Fortran source code using SWIG

本文关键字:创建 Python 模块 源代码 Fortran SWIG 使用      更新时间:2023-10-16

我正在从事一个项目,该项目涉及为用Fortran编写的程序创建Python接口。我做了一些研究并决定使用SWIG,首先向C++公开Fortran例程,然后用SWIG封装它们。但是,我很难让Python模块正常工作。

举个例子,我有一个Fortran函数:

function sum_array(input_array, length) result(sum)
implicit none
integer, value, intent(in) :: length
real(kind=8), intent(in), dimension(length) :: input_array
real(kind=8) :: sum
integer :: i
sum = 0.0
do i=1, length
   sum = sum + input_array(i)
end do
end function sum_array

带有C声明:

double sum_array(double* input_array, int length);

我使用的SWIG接口文件是:

%module sum_array
%{
   #define SWIG_FILE_WITH_INIT
   #include "sum_array.h"
%}
%include "numpy.i"
%init %{
   import_array();
%}
%apply (double* IN_ARRAY1, int DIM1) {(double* input_array, int length)};
%include "sum_array.h"

此接口文件使用numpy.i接口。

我正在将这段代码(使用make)编译成一个共享对象,如下所示:

$ swig -python -c++ -o sum_array_wrap.cpp sum_array.i
$ gfortran -c sum_array.f90 -o sum_array.o -fpic -fno-underscoring 
$ gcc -I/usr/include/python2.7 -c sum_array_wrap.cpp -o sum_array_wrap.o -fpic -std=c++0x
$ gfortran sum_array_wrap.o sum_array.o -o _sum_array.so -shared -Wl,-soname,_sum_array.so -lstdc++

当我尝试在Python中导入模块时,我会从:中得到"NameError:name‘sum_array’is not defined"

from numpy.random import rand
from _sum_array import *
input_array = rand(5)
sum = sum_array(input_array)

根据我从解释器中的help()获得的信息,我认为链接器没有在库中包含sum_array函数,我认为这就是问题所在。

关于如何让它发挥作用,有什么想法吗?

顺便说一句,关于其他工具而不是SWIG的建议非常受欢迎,因为这是我第一次这样做,也是我尝试过的唯一方法。

这一次的问题是名称篡改。fortran sompiler不使用它,因此导出符号名称为sym_array,但稍后您使用C++编译接口,因此链接器希望看到类似_Z9sum_arrayPdi的内容。解决方案是将标头内容包装到中

#ifdef __cplusplus
extern "C" {
#endif
double sum_array(double* input_array, int length);
#ifdef __cplusplus
}
#endif