I am trying to be able to pass a multidimensional Fortran array to a C++ program, in a C++ Fortran interoperating program. I have a basic idea of how passing the arrays from Fortran to C++ works; you pass a location of the array from Fortran to C++. Then C++ takes the flattened array and you have to do some algebraic calculation to find the element in a given multidimensional array.
I was able to successfully test this idea on a scalar array. It is not so hard to figure out the index of element in C++, because it is linearly mapped from Fortran index to C++ with offset of -1. Sample codes for Fortran and C++ are:
! Fortran main program
program fprogram
integer :: i
real*8 :: array(2)
array(1) = 1.0
array(2) = 2.0
! call cpp function
call cppfuncarray(array, 2)
write(*,*) array
end program
//cpp file
extern "C" {
void cppfuncarray_(double *array, int *imax);}
void cppfuncarray_(double *array, int *imax) {
int iMax = *imax;
for ( int i = 0; i < iMax; i++ ) {
array[i] = array + 1.0*i;
}
};
and the output will be array(1) = 1 and array(2) = 3. Now I am trying to pass multidimensional arrays such as A(2,2) or A(2,3,2) from Fortran to C++. I know that 2 dimensional array such as A(2,2) will be easy to figure out the flattened array in C++. But I reckon it might be a bit more challenging to locate elements in C++ for 3 or 4 dimensional arrays.
What is the correct way to construct a multidimensional array in C++ so that I can refer to elements in array A(k,j,i) in Fortran as A[i][j][k] in C++?
Thanks in advance!
array[j * n + i], whereiandjare indices,n- number of rows. (It is notarray[i * m + j], wheremis number of columns, because in Fortran multidimensional arrays stored in column major order) You can also generalize it to 3 or more dimensions.