I have a c++ program that looks as following:
using namespace std;
extern"C" {
void fortfunc_(int a[][4], int *size_x, int *size_y);
}
int main()
{
// size_x and size_y are dynamically determined at runtime
// setting them here directly for simplification
int size_x = 5;
int size_y = 4;
//we need to use 4 instead of size_y to prevent a mismatch with the int a[][4] definition in fortfunc_
int foo [size_x][4];
for (int i=0 ; i<size_x ; i++ )
{
for (int y=0 ; y<size_y ; y++ )
{
foo[i][y] = i+y;
}
}
fortfunc_(foo, &size_x, &size_y);
return 0;
}
The respective fortran program only prints the array and looks like this:
subroutine fortfunc(foo, size_x, size_y)
use :: ISO_C_BINDING
integer :: size_x, size_y
integer(c_int), dimension(size_y,size_x), intent(in) :: foo
integer :: i, y
do y = 1, size_x ! We reverse the loop order because of the reverse array order in fortran
do i = 1, size_y
print*, "col ",i,y, foo(i,y)
end do
print*, "row"
end do
return
end
When compiled with gfortran -c testF.f90 && g++ -c testC.cpp && g++ -o test testF.o testC.o -lgfortran && ./test
this works.
However, I would like to be able to dynamically determine the shape of the 2d array foo
in my main
function and call my external fortfunc_
function accordingly, instead of hardcoding int a[][4]
there. How can I modify my program to accomplish that?