hig*_*guy 3 c fortran fortran-iso-c-binding
我有一个很大的现有 Fortran95 代码。它用
real(dp), dimension(num) :: array
声明数组。
我想加入一些 C 代码,发现我可以通过编写 C 函数的接口并将数组声明为
use iso_c_binding
real(c_double), allocatable, target :: array(:)
我有调用 C 函数的工作 fortran 函数
call myfunction(c_loc(array));
将real(dp)数组传递给 myfunction需要什么?显然,我需要从中制作一个 C 指针(如何?)。除了复制数组还有其他方法吗?是否可以确保两种类型确实引用兼容的双精度数据块?最重要的是,该解决方案必须适用于 GNU 编译器。请注意,在现有 Fortran 代码中替换real(dp)为real(c_double)任何地方现在对我来说不是一个选择。
如果没有复制整个数组的替代方法,我将如何在界面中正确执行此操作?
小智 5
首先,我假设您将 dp 定义为某个模块中的参数。你可以简单地使用
integer, parameter :: dp = c_double
在那个模块中(并且有if (dp /= c_double) stop "Bletchful sytem"某个地方。
在 C 和 Fortran 之间传递数组的工作方式如下:
module foo
  use iso_c_binding
  private
  public :: bar
  interface
     subroutine bar(a,n) bind(C)
       import
       real(kind=c_double), dimension(*), intent(inout) :: a
       integer(c_size_t), value, intent(in) :: n
     end subroutine bar
  end interface
end module foo
你的 C 函数将是
void bar(double *a, size_t n)
编辑:
从 Fortran 调用 C 函数的方法是
program main
  use iso_c_binding
  use foo
  real(c_double), dimension(10) :: a
  call bar(a,size(a,kind=c_size_t))
  print *,a
end program main
编辑2:
如果您真的想每次都进行拷入/拷出,则可以执行以下操作
  subroutine bar2(array)
    real(kind=c_double), intent(inout), dimension(:) :: array
    real(kind=c_double), dimension(size(array)) :: a
    a = array  ! Copy in
    call bar(a,size(a,kind=c_size_t))
    array = a  ! Copy out
  end subroutine bar2
end module foo
但我不明白为什么这是必要的。
编辑3:
如果您担心 C 和 Fortran 数据类型之间不匹配,您可以编写一个通用包装器来解决这个问题。这是它的样子:
module foo
  use iso_c_binding
  implicit none
  private
  public :: bar
  interface
     subroutine bar_double(a,n) bind(C)
       import
       real(kind=c_double), dimension(*), intent(inout) :: a
       integer(c_size_t), value, intent(in) :: n
     end subroutine bar_double
  end interface
  interface
     subroutine bar_float(a,n) bind(C)
       import
       real(kind=c_float), dimension(*), intent(inout) :: a
       integer(c_size_t), value, intent(in) :: n
     end subroutine bar_float
  end interface
  interface bar
     module procedure bar_aux_double, bar_aux_float
  end interface bar
contains
  subroutine bar_aux_double (a)
    real(kind=c_double), dimension(:), intent(inout) :: a
    call bar_double (a, size(a,kind=c_size_t))
  end subroutine bar_aux_double
  subroutine bar_aux_float (a)
    real(kind=c_float), dimension(:), intent(inout) :: a
    call bar_float (a, size(a,kind=c_size_t))
  end subroutine bar_aux_float
end module foo
你的主程序可能看起来像
program main
  use foo
  integer, parameter :: dp = selected_real_kind(15)
  integer, parameter :: sp = selected_real_kind(6)
  real(dp), dimension(10) :: a_dp
  real(sp), dimension(10) :: a_sp
  call bar(a_dp)
  call bar(a_sp)
  print *,a_dp,a_sp
end program main
在那里你根本没有提到 iso_c_binding 。如果 dp 或 sp 没有包装函数,则编译将因缺少通用过程而失败。