DaP*_*hil 8 c variables file-io fortran fortran-iso-c-binding
我习惯了Fortran,我使用namelist顺序读入来从文件中获取变量.这允许我有一个看起来像这样的文件
&inputDataList
n = 1000.0 ! This is the first variable
m = 1e3 ! Second
l = -2 ! Last variable
/
Run Code Online (Sandbox Code Playgroud)
我可以通过它的名称命名变量,然后分配一个值以及后面的注释来说明变量实际是什么.装载非常简单
namelist /inputDataList/ n, m, l
open( 100, file = 'input.txt' )
read( unit = 100, nml = inputDataList )
close( 100 )
Run Code Online (Sandbox Code Playgroud)
现在我的问题是,C中有类似的东西吗?或者我是否必须通过在'='处切断字符串来手动执行此操作?
mil*_*cic 11
这是一个简单的例子,可以让你从C中读取Fortran名单.我使用了你在问题中提供的名单文件,input.txt
.
Fortran子程序nmlread_f.f90
(注意使用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
Run Code Online (Sandbox Code Playgroud)
C程序,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);
}
Run Code Online (Sandbox Code Playgroud)
还要注意n
,m
并且l
需要声明为指针,以便通过引用Fortran例程来传递它们.
在我的系统上,我使用英特尔编译器套件编译它(我的gcc和gfortran已经很久了,不要问):
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
Run Code Online (Sandbox Code Playgroud)
执行a.out
产生预期的输出:
0.0 0.0 0
Fortran procedure has n,m,l: 1000.000 1000.000 -2
1000.0 1000.0 -2
Run Code Online (Sandbox Code Playgroud)
您可以编辑上面的Fortran过程以使其更通用,例如,从C程序中指定名称列表文件名和列表名.