C equivalent to Fortran namelist

这一生的挚爱 提交于 2019-12-01 03:56:07

Here is a simple example that will let you read Fortran namelists from C. I used the namelist file that you provided in the question, input.txt.

Fortran subroutine nmlread_f.f90 (notice the use of ISO_C_BINDING):

subroutine namelistRead(n,m,l) bind(c,name='namelistRead')

  use,intrinsic :: iso_c_binding,only:c_float,c_int
  implicit none

  real(kind=c_float), intent(inout) :: n
  real(kind=c_float), intent(inout) :: m
  integer(kind=c_int),intent(inout) :: l

  namelist /inputDataList/ n,m,l

  open(unit=100,file='input.txt',status='old')
  read(unit=100,nml=inputDataList)
  close(unit=100)

  write(*,*)'Fortran procedure has n,m,l:',n,m,l

endsubroutine namelistRead

C program, nmlread_c.c:

#include <stdio.h>

void namelistRead(float *n, float *m, int *l);

int main()
{
  float n;
  float m;
  int   l;

  n = 0;
  m = 0;
  l = 0;

  printf("%5.1f %5.1f %3d\n",n,m,l);

  namelistRead(&n,&m,&l);

  printf("%5.1f %5.1f %3d\n",n,m,l);   
}

Also notice that n,m and l need to be declared as pointers in order to pass them by reference to the Fortran routine.

On my system I compile it with Intel suite of compilers (my gcc and gfortran are years old, don't ask):

ifort -c nmlread_f.f90
icc -c nmlread_c.c
icc nmlread_c.o nmlread_f.o /usr/local/intel/composerxe-2011.2.137/compiler/lib/intel64/libifcore.a

Executing a.out produces the expected output:

  0.0   0.0   0
 Fortran procedure has n,m,l:   1000.000       1000.000              -2
1000.0 1000.0  -2

You can edit the above Fortran procedure to make it more general, e.g. to specify namelist file name and list name from the C program.

I've made a test of above answer under GNU compilers v 4.6.3 and worked perfectly for me. Here's is what I did for the corresponding compilation:

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