c - 如何将常量字符串从 fortran 函数传递到 C

标签 c fortran filepath

我在将字符串从 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/

相关文章:

Java:从文件路径获取 URI

javascript - 当只有文件夹路径已知时,使用 javascript/jquery 从 url 获取当前文件名

c - 链接列表未按预期工作

c - 确定变量内容的字节长度

fortran - 显示 Fortran 中意图(out)和意图(inout)之间差异的有效程序

multithreading - Fortran 基本函数与基本子例程

javascript - ./和/in &lt;script&gt; src 属性之间有什么区别吗?

c++ - VB换行转义字符?

c - Mac C 程序在字符串初始值设定项上崩溃

segmentation-fault - Gfortran : Segmentation fault with long character