How to pass single dimension array from fortran to c [duplicate]

ぐ巨炮叔叔 提交于 2019-12-08 00:51:24

问题


I am passing a single dimension array to function from Fortran program to a C. The function get called but the values it gets are garbage. Here is my code

File: abc.f

program test
    real*4 :: a(4)
    data a / 1,2,3,4 /
    call test_func(a)
end program testFile: 

File: abc.c

int test_func(double a[]) {
    int i;

    for(i=0;i<4;i++) {
        printf("%f\n",a[i]);
    }

    return 0;
}

But if i pass integer instead of array then it is successfully passed.


回答1:


You should change your signature to

 void test_func(float a[], int arraylength);

Not only are you passing the wrong datatype, you are also reading more memory, then you passed in, which accounts for the garbage.

real is 4 bytes and double is 8 bytes, so you are reading twice as much memory beyond your array limit as you passed in which will cause undefined behaviour.

Another good idea would be to pass the length of the array as well. I don't know how this is in Fortran, but in C you are just reading a pointer, without any information how long that array is.



来源:https://stackoverflow.com/questions/20650636/how-to-pass-single-dimension-array-from-fortran-to-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!