How do I pass a 2D array in C++ to a Fortran subroutine?

前端 未结 3 1594
暖寄归人
暖寄归人 2020-12-29 16:27

I am writing a small C++ program which passes a 2-D array (of complex numbers) to a Fortran subroutine and receives it back filled with values. I wrote a version which passe

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 16:35

    Multidimensional arrays in Fortran are stored as flat column-major arrays in memory. They are not pointers to pointers—they're really just 1D arrays where you have to do some extra arithmetic to compute array indices.

    The correct way to pass the array from C++ is like this:

    extern "C" void carray_(struct cpx *A);
    ...
    struct cpx A[2*2];
    carray_(A);
    
    complex P[2][2];
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j < 2; j++)
        {
            // note order of indicies: A is column-major
            P[i][j] = std::complex(A[j*2 + i].r, A[j*2 + i].i);
        }
    }
    

提交回复
热议问题