1

我正在尝试调用在 Fortran 子例程中定义的全局字符串变量,在 C 中。C 代码是Cfile.c

#include <stdio.h>

typedef struct {
        int length;
        char* string;
} fstring;

extern fstring stringf_;
void fortfunc_();

int main() {
        fstring stringC = stringf_;
        stringC.string[stringC.length-1] = '\0';
        printf("%s \n",stringC.string);
        return 0;
}

和 FORTRAN 代码是Ffile.f

subroutine fortfunc()
  
        character*30 string
        common/stringF/ string
        string = 'this is a string in FROTRAN77'

return
end

它编译为:

gcc -c Cfile.c
gfortran -c -std=legacy Ffile.f
gfortran -c file.out -std=legacy Cfile.o Ffile.o

但是在运行时出现分段错误。我不明白我什么时候违反了内存边界。

我的操作系统是:

Linux ubuntu 4.15.0-39-generic #42-Ubuntu SMP Tue Oct 23 15:48:01 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

我的编译器是:

GNU Fortran (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0

gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0

如果您能帮助我知道我的错误在哪里以及如何解决,我将不胜感激?在 Fortran 中定义全局变量然后在 C 中调用它的其他解决方案也受到欢迎。

4

1 回答 1

2

根据我在这里和Reddit上得到的评论,我现在有一个可以工作的代码。C代码:

#include <stdio.h>

typedef struct {
    char s[30];
} fstring;

extern fstring stringf_;

int main() {
    fstring stringc = stringf_;
    stringc.s[29] = '\0';
    printf("%s\n",stringc.s);
    return 0;
}

和 FORTRAN 代码:

        BLOCK DATA

                CHARACTER*30 S
                COMMON /STRINGF/ S
                DATA S /'this is a string in FROTRAN77'/

        end

发生段错误是因为传递的stringC.length值为零。这意味着与我在此处从 FORTRAN 端调用字符串时所遵循的示例不同,它不会将长度作为整数传递!

于 2018-12-02T00:09:18.320 回答