2011-08-15 13 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? ()(gdb) #0 0x0000000a00000df3? () アドレス0xa00000df3 #スタートで1 0x0000000100000d0c() – 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配列は(Cのような他の場所から来た場合でも)1つのインデックスが付けられます。だから、これは1から始めるべきです。また、0が正しければ、サイズは間違っています。あなたは何かをしたいです

do concurrent (i=1:h) 

この変更で、それは私のために働いています。

+0

ありがとう、私は今、とても馬鹿だと感じています... – tracius01

+0

Fortranの配列は*知っている* 1ベース。どこかでそれを読んでいることの暗い記憶、はい。 – zwol

+0

あなたは最初に、どちらかの方法でそれを持ってきました... –

関連する問題