在C中从Fortran调用全局字符串变量会导致分段错误 [英] Calling a global string variable from Fortran in C causes segmentation fault

查看:92
本文介绍了在C中从Fortran调用全局字符串变量会导致分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C中调用Fortran子例程中定义的全局字符串变量.C代码为Cfile.c:

I'm trying to call a global string variable which is defined in a Fortran subroutine, in C. the C code is 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:

and FORTRAN code is 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

但是运行时我遇到了分割错误.我不明白何时违反内存限制.

but when running I get the segmentation fault. I do not understand when I'm violating the memory boundaries though.

我的操作系统是:

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

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

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

gcc(Ubuntu 7.3.0-27ubuntu1〜18.04)7.3.0

gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0

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

I would appreciate if you could help me know where is my mistake and how I can solve it? other solutions to define a global variable in Fortran and then calling it in C are also welcomed.

推荐答案

基于我在此处和

Based on the comments I got here and on Reddit, I now have a code which works. The C code:

#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代码:

and FORTRAN code:

        BLOCK DATA

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

        end

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

The segfault was happening because the passed stringC.length value is zero. It means unlike the example I was following here when calling a string from the FORTRAN side it does not pass the length as an integer!

这篇关于在C中从Fortran调用全局字符串变量会导致分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆