【发布时间】:2016-07-05 18:20:26
【问题描述】:
我在将字符串从 Fortran 传递到 C 时遇到问题。C 代码将包含文件路径的字符串传递给 Fortran 函数。该函数读取文件并应返回一个两个字符的字符串。
这是我的 C 代码
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/time.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <time.h>
#include <ctype.h>
using namespace std;
extern "C" void read_id_type_(char *file_path, char *id_type, size_t *path_len_file);
int main(int argc, char **argv) {
char path[500],id_type[2];
char *dir_path, *file_path;
dir_path=path;
size_t path_len=strlen(dir_path);
file_path=strcat(path,"/rnspar_mpt1.dat");
size_t path_len_file=strlen(file_path);
read_id_type_(file_path,id_type,&path_len_file);
printf("id_type is %s\n",id_type);
return EXIT_SUCCESS ;
}
这是我的 Fortran 函数
integer function read_id_type(filename,id_type,path_len)
implicit none
integer :: nrg, nrf, nrf_deform, nrgin,path_len
character(400) :: filename
character(2) :: id_type,EQ_point
filename=filename(1:path_len)
write(*,*),"Reading file", filename
open(unit = 1,file = trim(filename), status='old')
read(1,'(4i5)') nrg
read(1,'(4i5)') nrf
read(1,'(2i5,2(3x,a2))') nrf_deform, nrgin, id_type, EQ_point
close(1)
print *,"Id_type=",id_type
read_id_type = 0
end function read_id_type
输出是:
Id_type=IR (From the Fortran side)
id_type is IRV2? (From the C side)
C 代码中的输出应该只有前两个字符。 任何帮助将不胜感激
【问题讨论】:
-
顺便提一下,
<iostream>、<iomanip>、<fstream>和<sstream>是 C++ 头文件,using namespace std;是 C++ 语句。所以这段代码不会编译成C。虽然主要代码是纯C风格的,但它只会编译成C++。 -
在 stackoverflow.com/questions/8207997/… 有一个将字符串从 C 传递到 Fortran 的示例。我建议研究它以了解 C 和 Fortran 字符串之间的区别。下一步:进一步研究 ISO C Binding 添加返回参数。 Stack Overflow 上有很多例子。