简体   繁体   English

使用延迟形状数组从C调用Fortran

[英]Calling Fortran from C with deferred shape array

Is it possible to call a Fortran subroutine from C/C++, where one of the Fortran arguments is a deferred-shape array? 是否可以从C / C ++调用Fortran子例程,而其中Fortran参数之一是延迟形状数组? (Hopefully I'm using the term "deferred-shape" correctly.) (希望我正确使用了“ deferred-shape”一词。)

In the example below, subr1() uses explicit-shape, and works fine, but subr2() uses deferred-shape and causes a segfault. 在下面的示例中, subr1()使用显式形状,并且工作正常,但是subr2()使用延迟形状并导致段错误。 This question indicates that one needs an explicit interface to call subr2() from another Fortran subroutine, but I'm trying to call from C. Is it just not possible to do it this way? 这个问题表明一个人需要一个显式的接口来从另一个Fortran子例程中调用subr2() ,但是我试图从C中进行调用。

In the real problem the length of the array would be more complicated -- which is why, in an ideal world, I would like to use the deferred-shape version. 在实际的问题中,数组的长度会更复杂-这就是为什么在理想的世界中,我想使用延迟形状的版本。 (Of course in an ideal world, I wouldn't be mixing Fortran and C at all.) (当然,在理想的世界中,我根本不会混合使用Fortran和C。)

test_array_c.c test_array_c.c

#include <malloc.h>

extern void subr1_(int*, int*);
extern void subr2_(int*, int*);

int main(int argc, char **argv){

  int N,i;
  int *data;

  // create an array
  N=3;
  data=(int*)malloc(N*sizeof(int));
  for (i=0;i<N;i++) data[i]=i;

  // pass array to fortran functions
  subr1_(&N,data);
  subr2_(&N,data);

  // free
  free(data);
}

test_array_f90.f90 test_array_f90.f90

subroutine subr1(n,data)
  implicit none

  integer,intent(in) :: n
  integer,intent(in) :: data(n)
  integer :: i

  do i=1,n
    print*, data(i)
  enddo

end subroutine

subroutine subr2(n,data)
  implicit none

  integer,intent(in) :: n
  integer,intent(in) :: data(:)
  integer :: i

  do i=1,n
    print*, data(i)
  enddo

end subroutine

command line build/run 命令行构建/运行

user@host:~$ gcc -g -O0 -c test_array_c.c
user@host:~$ gfortran -g -O0 -c test_array_f90.f90
user@host:~$ gcc -o test_array test_array_c.o test_array_f90.o -lgfortran
user@host:~$ ./test_array
           0
           1
           2
Segmentation fault (core dumped)

The term is "assumed-shape" array. 该术语是“假定形状”阵列。 As a practical matter of compiler implementation, its likely to be passed as some sort of structure that won't be consistent C. Which explains the segmentation fault. 作为编译器实现的一个实际问题,它很可能会以某种与C不一致的结构来传递。这解释了分段错误。

In this era, I recommend mixing Fortran and C via the ISO C Binding. 在这个时代,我建议通过ISO C绑定混合Fortran和C。 But that won't help here because assumed-shape arrays aren't supported by the ISO C Binding, or at least not by the Fortran 2003 version. 但这在这里无济于事,因为ISO C绑定(或者至少Fortran 2003版本不支持)不支持假定形状的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM