【问题标题】:How to pass a constant string from fortran function to C如何将常量字符串从fortran函数传递给C
【发布时间】: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 代码中的输出应该只有前两个字符。 任何帮助将不胜感激

【问题讨论】:

  • 顺便提一下,&lt;iostream&gt;、&lt;iomanip&gt;、&lt;fstream&gt; 和 &lt;sstream&gt; 是 C++ 头文件,using namespace std; 是 C++ 语句。所以这段代码不会编译成C。虽然主要代码是纯C风格的,但它只会编译成C++。
  • 在 stackoverflow.com/questions/8207997/… 有一个将字符串从 C 传递到 Fortran 的示例。我建议研究它以了解 C 和 Fortran 字符串之间的区别。下一步:进一步研究 ISO C Binding 添加返回参数。 Stack Overflow 上有很多例子。

标签: c fortran filepath


【解决方案1】:

代替

id_type[2]

至少做到这一点

id_type[3]

并在调用 Fortran 例程后将第 3 个rd 字符(在索引 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 );

【讨论】:

  • 我一直在尝试 id_type[3] 并且输出几乎相同:id_type is IR??h
  • 如果你真的将第 3 个字符设置为整数 0,那么 C 输出函数将不会显示超过前 2 个字符。所以,再试一次。 ;-)
  • 非常感谢!结果证明解决方案更简单。关键是空终止字符串。我正在使用id_type[2]='\0'; ,它工作得很好!
猜你喜欢
  • 2014-10-25
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
相关资源
最近更新 更多