mar*_*260 3 c c++ multilingual char
我正在将一些传统的Fortran77代码迁移到C/C++.在Fortran77代码中,如果从文件中读入8个字符,则可以将它们存储在real*8类型的变量中而不会出现问题.
是否有可能在C或C++中做类似的事情?如果是这样,我该怎么做?我无法在互联网上找到任何解决方案.我需要使用C/C++读取8个字符并将它们存储在double类型的变量中,然后传递回Fortran并对应于原始的真实*8变量.
非常感谢您的帮助.
编辑: 为了回应@sixlettervariables,我只是澄清一下我的用例.我对他的建议的问题是我在运行时只知道每一行的格式(即哪些字段是字符串,哪些数字),因此我无法知道结构应该静态的成员.这些字段还需要按读入顺序占用连续的内存块.
具体地说,在程序的一次运行中,每行的格式可能是:f1:string,f2:number,f3:number,f4:string,但在另一个f1:string中,f2:string,f3:string,f4:number ,f5:数字.对于我需要的第一种情况:
struct { char[8] f1; double f2; double f3; char[8] f4}
Run Code Online (Sandbox Code Playgroud)
对于第二个我需要:
struct { char[8] f1; char[8] f2; char[8] f3; double f4; double f5}
Run Code Online (Sandbox Code Playgroud)
也许有一些方法可以用模板做到这一点?
您不需要将它们存储在doubleJust中,因为Fortran需要这样做.实际上,你绝对不应该在你的C/C++代码中这样做.
只需将字符数据存储在字符数组中即可.
如果你正在混合使用Fortran和C/C++,那么两人在他们的ABI之外并不知道彼此.从C方面你可以简单地声称 Fortran接口采用一个字符数组,而实际上它需要一个双精度数组.Fortran方面也是如此.
从C方面:
extern void FCHARS(char* str, int length);
/* ... */
int flength = 0; /* optional: length of the string in Fortran terms */
char str[9]; /* in C/C++ add one for \0 at the end */
/* read in up to a block of 8 */
fgets(str, sizeof(str), fp);
/* At this point if you know the 8 characters are space padded to their end
* you have no more work to do, otherwise you may need to fill from the right
* with spaces.
*/
{
size_t ii = sizeof(str) - 1;
while (ii > 0 && str[ii - 1] == '\0') {
str[ii - 1] = ' ';
flength = ii--; /* optional: keep track of our unpadded length */
}
}
/* Once you've space padded the string you can call your Fortran method.
* If your Fortran method accepts a string of unknown length, supply
* `flength`. If your Fortran method expects a string of a fixed length, pass
* the size of `str` (excluding '\0') instead.
*/
FCHARS(str, flength);
Run Code Online (Sandbox Code Playgroud)
只要您遵循Fortran编译器的ABI要求(例如,CDECL,隐藏的字符串长度通过交叉传递),您就可以了.