How to convert a C-utility into a subroutine and call it from gfortran?

Tobias Burnus burnus@net-b.de
Tue Jun 19 13:04:00 GMT 2007


Arjan van Dijk schrieb:
>> a) The size of the array is known (at run time or compile time): simply
>> pass the arrays from fortran
>>     
> Very often I will know the size ahead. Solution 1 should be okay.
> Can you please explicitly tell me how to pass the fortran arrays
> to the C-routine and vise versa?
>   
Well, something like the following works here (I did not spend much time
thinking on storage/array index order, i.e. on foo[nx][ny] vs. foo(ny,nx).)

#include <stdio.h>
int test_(char *file, int nx, int ny, float *array)
{
   int i, j;
   printf("Filename: '%s'\n", file);
   for(j = 0; j < nx; j++)
     for(i = 0; i < ny; i++)
       array[j*nx+i] = (float) j;
   return 0;
}


program x
 implicit none
 interface
   integer function test(file, nx, ny, array)
      character(len=*), intent(in)   :: file
      integer, intent(in), value     :: nx, ny
      real, dimension(*),intent(out) :: array
   end function test
 end interface
 real, dimension(:,:), allocatable :: array
 integer :: nx, ny, result, i, j
 nx = 3
 ny = 5
 allocate(array(nx,ny))
 result = test("MyFile"//achar(0), nx, ny, array)
 do i = 1, ny
   print *, array(:,i)
 end do
end program x



Variant for the C program, which makes it easier in terms of indixes:

int test2_(char *file, int nx, int ny, float array[ny][nx])
{
   int i, j;
   printf("Filename: %s\n", file);
   for(i = 0; i < nx; i++)
     for(j = 0; j < ny; j++)
       array[j][i] = (float) j;
   return 0;
}


Tobias



More information about the Fortran mailing list