我正在将一些旧版 Fortran77 代码迁移到 C/C++。在Fortran77代码中,如果从文件中读入8个字符,则可以将它们存储在real*8类型的变量中,没有问题。
是否可以在 C 或 C++ 中做类似的事情?如果是这样,我该怎么做?我无法在互联网上找到任何解决方案。我需要使用 C/C++ 读取 8 个字符并将它们存储在 double 类型的变量中,然后将其传递回 Fortran 并对应于原始的 real*8 变量。
非常感谢您的帮助。
EDIT:为了回应@sixlettervariables,我将进一步澄清我的用例。我对他的建议的问题是,我只知道运行时每行的格式(即哪些字段是字符串,哪些字段是数字),因此我不知道该结构应该静态具有哪些成员。这些字段还需要按照读入的顺序占用连续的内存块。
具体来说,在程序的一次运行中,每一行的格式可能是:f1:字符串、f2:数字、f3:数字、f4:字符串,但在另一个f1:字符串、f2:字符串、f3:字符串、f4:数字、f5:数字。对于第一种情况我需要:
struct { char[8] f1; double f2; double f3; char[8] f4}
对于第二个我需要:
struct { char[8] f1; char[8] f2; char[8] f3; double f4; double f5}
也许有某种方法可以使用模板来做到这一点?
您不需要将它们存储在double
只是因为 Fortran 需要这样做。事实上,你绝对不应该在您的 C/C++ 代码中执行此操作。
只需将字符数据存储在字符数组中即可。
如果您混合使用 Fortran 和 C/C++,则两者除了 ABI 之外对彼此一无所知。从C端你可以简单地claimFortran 接口接受一个字符数组,而实际上它需要一个双精度数组。 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);
只要您遵循 C/C++ 代码中 Fortran 编译器的 ABI 要求(例如 CDECL、交错传递的隐藏字符串长度),就可以了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)