【发布时间】:2021-09-21 19:57:43
【问题描述】:
我目前需要将 Fortran 子例程包装到 Python 中。我想使用 Cython 来完成它,我现在正在处理较小的任务,以便在处理实际脚本之前对我正在做的事情有一些基本的了解,因为它们非常大,涉及数十个派生类型和子例程。
我对 Fortran、C 和 Cython 非常陌生,我正在尝试包装一个基本的派生类型和子例程。但是,当我尝试编译时,由于派生类型“不可互操作”而出现错误。
初始模块可以在下面找到: "summation.f90"
module gfunc_module
implicit none
type :: geo
real, dimension(1:2) :: coordinates
real :: weight
end type
contains
subroutine gfunc(v1, v2, final_v)
type(geo), intent(in) :: v1, v2
type(geo), intent(out) ::final_v
final_v%coordinates = v1%coordinates * v1%weight + v2%coordinates + v2%weight
final_v%weight = v1%weight + v2%weight
end subroutine
end module
然后,我使用 iso_c_binding 包装它:(pysummation.f90)
module gfunc1_interface
use iso_c_binding
use gfunc_module
implicit none
type, bind(c) :: geo
real(c_float), dimension(1:2) :: coordinates
real(c_float) :: weight
contains
subroutine c_gfunc(v1, v2, final_v) bind(c)
type(geo), intent(in) :: v1, v2
type(geo), intent(out) :: final_v
call gfunc(v1, v2, final_v)
end subroutine
end module
然后,我写了一个头文件:(pysummation.h)
struct geo {
float coordinates[2];
float weight;
}
extern void c_gfunc(geo *v1, geo *v2, geo *final_v);
我的 cython 文件(pysummation.pyx):
cdef extern from "pysummation.h":
cdef struct geo:
float coordinates[2]
float weight
void c_gfunc(geo *v1, geo *v2, geo *final_v)
def f(geo v1, geo v2):
cdef:
geo value
c_gfunc(<geo*>&v1, <geo*>&v2, <geo*>&value)
return value
最后,我的设置文件(setup.py):
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# This line only needed if building with NumPy in Cython file.
from numpy import get_include
from os import system
# compile the fortran modules without linking
fortran_mod_comp = 'gfortran summation.f90 -c -o summation.o -O3 -fPIC'
print fortran_mod_comp
system(fortran_mod_comp)
shared_obj_comp = 'gfortran pysummation.f90 -c -o pysummation.o -O3 -fPIC'
print shared_obj_comp
system(shared_obj_comp)
ext_modules = [Extension(# module name:
'pygfunc',
# source file:
['pysummation.pyx'],
# other compile args for gcc
extra_compile_args=['-fPIC', '-O3'],
# other files to link to
extra_link_args=['summation.o', 'pysummation.o'])]
setup(name = 'pygfunc',
cmdclass = {'build_ext': build_ext},
# Needed if building with NumPy.
# This includes the NumPy headers when compiling.
include_dirs = [get_include()],
ext_modules = ext_modules)
当我尝试编译我的脚本时,我收到以下错误:
- (1) 处“geo”的派生类型定义已定义。
我知道是因为我告诉 Fortran 使用我的模块,该模块已经定义了“geo”类型,但我认为因为我想使用 iso_c_binding,所以我必须重新定义它。
我得到的第二个错误是
- 变量“v1”是 BIND(C) 过程的伪参数,但不能与 C 互操作,因为派生类型“geo”不能与 C 互操作。
这发生在所有类型(geo)的变量上。我只是想知道是否有人可以阐明 c 互操作性如何与数组和派生类型有关?
我认识到我的代码中可能还有许多其他错误。不过,在开始排除其他故障之前,我想至少解决这几个问题。
【问题讨论】:
-
<geo*>&v1- 你不应该需要这些指针转换。通过添加演员表,您几乎肯定会隐藏真正的错误
标签: c fortran cython fortran-iso-c-binding