[英]How to pass a array of string from fortran to c?
I want to pass a array of string which I filled in fortran code to C. However, every times I tried to check the result I found that each one of the character string is printed as a whole array in C. Can anyone help through this? 我想将我填写了fortran代码的字符串数组传递给C。但是,每次尝试检查结果时,我发现每个字符串都在C中打印为整个数组。任何人都可以帮忙? This is fortran part of code:
这是代码的fortran部分:
SUBROUTINE hello (Characters)
CHARACTER*(16) Characters(5)
Characters=(/"ABCD","BCDF","CVFG","D HG","J67F"/)
return
END
and this is C code: 这是C代码:
void hello_(char *[16]);
int main(int argc,char **args)
{
char Character2[5][16];
int j;
hello_(&Character2);
for(j=0;j<5;j++){
printf("String [ %d ] = %s \n",j,Character2[j]);
}
return 0;
}
The results I get is this: 我得到的结果是这样的:
String [ 0 ] = ABCD BCDF CVFG D HG J67F `����U
String [ 1 ] = BCDF CVFG D HG J67F `����U
String [ 2 ] = CVFG D HG J67F `����U
String [ 3 ] = D HG J67F `����U
String [ 4 ] = J67F `����U
I want to know why I can't access to each one of those strings which I passed from fortran to C? 我想知道为什么我无法访问从fortran传递到C的那些字符串中的每一个? I mean, how can I make sure that ,like, Character2[1] is exactly what I made in fortran, "ABCD"!
我的意思是,我如何才能确保像Character2 [1]一样正是我在fortran中创建的“ ABCD”! Thanks
谢谢
Since the FORTRAN strings are not NUL terminated, the C code will not be able to detect the end of the string being printed. 由于FORTRAN字符串不是NUL终止的,因此C代码将无法检测到正在打印的字符串的结尾。
Since your strings are meant to be no longer than a certain length, you can specify that in your print statement (although, it is unclear to me that FORTRAN will fill with spaces if you don't provide a long enough string): 由于您的字符串长度不得超过一定长度,因此您可以在print语句中指定该字符串(尽管我不清楚,如果您不提供足够长的字符串,那么FORTRAN是否会用空格填充):
printf("String [ %d ] = %.4s \n",j,Character2[j]);
If your FORTRAN code knows it will be called from C, then it should add the NUL byte to the strings before returning the array back to the caller. 如果您的FORTRAN代码知道它将由C调用,则应在将数组返回给调用方之前将NUL字节添加到字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.