我可以用gfortran创建共享库吗?
我想制作一个.so文件,以便在Python中使用。请问我该如何从Fortran源代码创建共享库呢?
我尝试了下面的代码。
gfortran -c mod.f90
#gfortran -c sub1.f90
gfortran -c func.f90
gfortran -shared -fPIC -o func.so func.f90 mod.o
但是我在Python中无法导入它。我在Fortran源代码中使用了模块文件,并且从Python中导入了Fortran源代码。我不确定我这样做是否正确。
[===>14:47:59]f1:python
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import func
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initfunc)
func.f90
-----------------------------------------
program func
use mod_test
switch1 = .true.
switch2 = .false.
x = 1.2
!call test(x, z)
print *, b, str, z, switch1, switch2
!print *, 'hello'
end program func
-----------------------------------------
mod.f90
-----------------------------------------
module mod_test
!implicit none
integer a
real x, y, z
real*8 :: b = 3.4
logical*2 switch1, switch2
character*5, parameter :: str = 'good'
end module mod_test
-----------------------------------------
sub1.f90
-----------------------------------------
subroutine test(input, output)
real, intent(in) :: input
real, intent(out) :: output
output = (input + input)
end subroutine
-----------------------------------------
1 个回答
11
你需要一些“粘合剂”来连接Fortran和Python。可以看看F2PY - Fortran到Python的接口生成器
编辑:示例:
f2py -c -m func func.f90 mod.f90 sub1.f90
python
>>> import func
>>> dir(func)
['__doc__', '__file__', '__name__', '__version__', 'mod_test', 'test']
编辑2:如果你想从Python执行func.f90中的代码,我觉得你必须把它从程序改成一个子程序。