c - 段错误 C 和 Fortran

标签 c fortran fortran-iso-c-binding

------ main.c---------

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string.h>

int main()
{   
    char* lib_name = "./a.out";
    int array[5] = {1,2,3,4,5};
    int size_a = sizeof(array)/sizeof(int);            
    void* handle = dlopen(lib_name, RTLD_NOW);
    if (handle) {
        printf("[%s] dlopen(\"%s\", RTLD_NOW): incarcare finalizata\n", 
           __FILE__, lib_name);
    }
    else {
        printf("[%s] nu poate fi deschis: %s\n", __FILE__, dlerror());
        exit(EXIT_FAILURE);
    }
    void (*subrutine_fortran)(int*, int*) = dlsym(handle, "putere");
    if (subrutine_fortran) {
        printf("[%s] dlsym(handle, \"_set_name\"): simbol gasit\n", __FILE__);
    }
    else {
        printf("[%s] simbol negasit: %s\n", __FILE__, dlerror());
        exit(EXIT_FAILURE);
    }



    subrutine_fortran(&array,&size_a);
    //dlclose(handle);
    for(int i=1;i<4;i++) {
    array[i]=array[i]+1;
    }
}

------你好.f90 --------

subroutine putere(a,h) bind(c)
    use ISO_C_BINDING
    implicit none
    integer(c_int) :: h
    integer(c_int), dimension(h) :: a
    integer i
    do concurrent (i=0:5)
        a(i)=a(i)*10
    end do
    !write (*,*) a
end subroutine

当我循环遍历数组元素时:

for(int i=1;i<4;i++) {
  array[i]=array[i]+1;
}

我遇到段错误。

当我写的时候它不会发生:

array[3]=array[3]+1

最佳答案

您的 C 代码是这样的:

int array[5] = {1,2,3,4,5};
int size_a = sizeof(array)/sizeof(int);            

subrutine_fortran(&array,&size_a);

你的 Fortran 代码是这样的:

subroutine putere(a,h) bind(c)
    use ISO_C_BINDING
    implicit none
    integer(c_int) :: h
    integer(c_int), dimension(h) :: a
    integer i
    do concurrent (i=0:5)
        a(i)=a(i)*10
    end do
    !write (*,*) a
end subroutine

这在很多方面都是错误的 - 正如 Zack 指出的那样,Fortran 数组是 1 索引的(即使它们来自其他地方,例如 C)。所以应该从 1 开始。此外,如果 0 是正确的,则大小将是错误的。你想要类似的东西

    do concurrent (i=1:h)

有了这个改变,它对我有用。

关于c - 段错误 C 和 Fortran,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7067678/

相关文章:

c - C中的回文数,字符串错误

c - for循环中的本地计数器变量

arrays - 具有显式 double 的 Fortran 数组

fortran - ISO_C_BINDING 从 Fortran 调用 C 例程(使用 double 和数组)

c - 将 Expokit 翻译成 C

c++ - 不同 Fortran 和 C 供应商之间的 ISO_C_BINDING

c - 两个寄存器的位声明

C++ 匿名结构异常定义

syntax - 奇数 Fortran 指针语法

c - 在 Fortran 派生类型中保存指向 C 函数的指针