简体   繁体   中英

can not correctly pass an array when calling a fortran function from c

I need to call a fortran function from c and one of the parameter is an array, the c code is:

float x[18] = {...};
pot = f_(x);

where x is an float array with 18 elements, and the fortran code is

function f(x,xc,im) result(pot)
  real,dimension(1:18),intent(in)::x
  real,dimension(:),optional,intent(in)::xc
  integer,optional,intent(in)::im
  do i=1,18
     write (*,*) x(i)
  enddo
  ...
end function f

The x array written by fortran function has different element values from the one in c code, can someone help me here? The compilers I use are icc and ifort and I used ifort to link the *.o files. Thanks

Fortran subroutines with optional arguments are not interoperable with C. The caller side must somehow signalize when not passing an optional argument. Some fortran compilers would pass a null pointer (see eg this thread in the GNU Fortran mailing list ]) but some may behave completely differently.

I'd anyway strongly suggest to use the bind(C) on the Fortran side when interoperating between Fortran and C. (See for some of the arguments here ). Your Fortran code would look then something like this:

module test
  use iso_c_binding
  implicit none

  integer, parameter :: rp = c_float

contains

  function ff(xx) result(pot) bind(c)
    real(rp), intent(in) :: xx(18)
    real(rp) :: pot

    integer :: ii

    do ii = 1, 18
      write(*,*) xx(ii)
    end do
    pot = -1.0_rp

  end function ff

end module test

While in C you'd write:

#include <stdio.h>

float ff(float *);

int main()
{

  float xx[18], res;
  int ii;

  for (ii = 0; ii < 18; ++ii) {
    xx[ii] = (float) ii;
  }
  res = ff(xx);
  printf("Result: %f\n", res);
}   

When you now specify optional on the Fortran side, you would get an error message with gfortran at least. Strangely, ifort does not give any error message, but that does not necessarily mean, that its behaviour is well defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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