2011-08-15 38 views
0

------ main.c中---------段故障C和Fortran

#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; 
    } 
} 

------ -------- hello.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 
+2

如果你在調試器中運行你的代碼,哪一行發生seg-fault? –

+2

Fortran數組是基於1還是0? (不是一個修辭問題。) – zwol

+0

程序收到信號EXC_BAD_ACCESS,無法訪問內存。 原因:地址處的KERN_INVALID_ADDRESS:0x0000000a00000df3 0x0000000a00000df3 in ?? ()(gdb)其中 #0 0x0000000a00000df3在? () 無法訪問內存地址0xa00000df3 #1 0x0000000100000d0c在start() – tracius01

回答

2

你的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) 

隨着這種變化,它適用於我。

+0

謝謝,我現在覺得這麼愚蠢...... – tracius01

+0

我不希望聲明*知道* Fortran數組是1爲主。對某個地方的閱讀暗淡記憶,是的。 – zwol

+0

你先拿出來,無論哪種方式...... –