gpt4 book ai didi

c - 如何将外部类型的参数从 C 传递到 Fortran

转载 作者:行者123 更新时间:2023-11-30 17:52:24 28 4
gpt4 key购买 nike

假设我在 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?

最佳答案

这有效,您必须使用指针:

void op(double *x, double *f) {
*f = pow(*x, 2);
}

void main() {
exec_(&op);
}

subroutine exec(routine)

implicit none

external :: routine
real(kind(1.d0)) :: res

call routine(2.0d0, res)
print *, "Fortran Result: res = ", res

end subroutine exec

不要使用 kind=8 它不声明 8 字节实数,而是声明类型编号为 8 的处理器相关类型。即使是旧的非标准 real*8 也会变得更好。

但最好使用 Fortran 2003 c 互操作性和 iso_c_binding 模块:

f.f90

subroutine exec(routine_c) bind(C,name="exec_") use iso_c_binding implicit none

    abstract interface
subroutine sub(a,b) bind(C)
use iso_c_binding
implicit none
real(c_double),value :: a
real(c_double) :: b
end subroutine
end interface

type(c_funptr),value :: routine_c
real(c_double) :: res
procedure(sub),pointer :: routine

call c_f_procpointer(routine_c,routine)

call routine(2.0d0, res)
print *, "Fortran Result: res = ", res

end subroutine exec

抄送

#include <math.h>
void op(double x, double *f) {
*f = pow(x, 2.0);
}

int main() {
extern void exec_(void (*) (double, double *));
exec_(&op);
return 0;
}

编译:

 gfortran c.c f.f90 -Wall -g -fbacktrace -fcheck=all
cc1: warning: command line option ‘-fbacktrace’ is valid for Fortran but not for C [enabled by default]
cc1: warning: command line option ‘-fcheck=all’ is valid for Fortran but not for C [enabled by default]
./a.out
Fortran Result: res = 4.0000000000000000

关于c - 如何将外部类型的参数从 C 传递到 Fortran,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238098/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com