Calling Fortran from C with deferred shape array

夙愿已清 提交于 2020-01-25 03:46:09

问题


Is it possible to call a Fortran subroutine from C/C++, where one of the Fortran arguments is a deferred-shape array? (Hopefully I'm using the term "deferred-shape" correctly.)

In the example below, subr1() uses explicit-shape, and works fine, but subr2() uses deferred-shape and causes a segfault. 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?

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.)

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

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)

回答1:


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.

In this era, I recommend mixing Fortran and C via the ISO C Binding. 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.



来源:https://stackoverflow.com/questions/21397188/calling-fortran-from-c-with-deferred-shape-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!