假设我在Fortran中有以下子例程
subroutine exec(routine)
implicit none
external :: routine
real(kind=8) :: res
call routine(2.0d0, res)
print *, "Fortran Result: res = ", res
end subroutine exec
该子例程接收外部例程作为参数 . 现在,假设这个例程是用C编写的,我还需要从C调用Fortran例程 exec . 像这样:
void op(double x, double *f) {
*f = pow(x, 2);
}
void main() {
exec_(op);
}
我知道,如果不是传递一个外部子程序,而是传递一个整数,一个double或另一个传统类型,它会起作用,但是这个代码会返回分段错误 . 有没有办法将类型为external的参数从C传递给Fortran?
1 回答
这有效,你必须使用指针:
不要使用
kind=8
它不会声明8字节真实,而是处理器相关类型,类型为8.即使旧的和非标准的real*8
会更好 .但最好使用Fortran 2003 c互操作性和
iso_c_binding
模块:f.f90
type(c_funptr),value :: routine_c
real(c_double):: res
procedure(sub),pointer :: routine
调用c_f_procpointer(routine_c,routine)
呼叫例程(2.0d0,res)
print *,“Fortran结果:res =”,res
结束子程序执行
C.C
汇编: