我在将字符串从 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 代码中的输出应该只有前两个字符。 任何帮助将不胜感激
最佳答案
而不是
id_type[2]
至少做到这一点
id_type[3]
并在调用 Fortran 例程后将第 3 个 字符(索引 2)设置为整数 0,否则它将不是 C 能够理解的以零结尾的字符串。
<小时/>由于当前代码尝试输出非零结尾的字符串,因此它会访问数组之外的内存,并具有正式的未定义行为。
有了 UB,任何事情或什么都没有,或者你期望的事情都有可能发生。
你刚刚得到了一些奇怪的额外字符。
<小时/>该字符串在 Fortran 中正确显示,因为您已在其中指定了其长度,
character(2) :: id_type
C 中并没有真正对应的功能,但在 C++ 中,您可以使用长度为 2 的 std::string
并将其缓冲区传递给 Fortran 例程,
std::string id_type( 2, ' ' );
//...
read_id_type_( file_path, &id_type[0], &path_len_file );
关于c - 如何将常量字符串从 fortran 函数传递到 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38210107/