簡體   English   中英

如何將常量字符串從fortran函數傳遞給C

[英]How to pass a constant string from fortran function to C

我在將字符串從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]

並設置第三字符(索引2)該呼叫到Fortran例程之后為整數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 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM