Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Beginner
6 Views

Passing a two-dimensional dynamic array from CPP to FORTRAN

Hello,

Can't run a mixed language program with dynamical array.

CPP call FORTRAN  as listed below.

CPP main program calls a fortran sub with the dynamic 2d array passing.

Compiling and linking phase was successful. However,

the following message is displayed, after execution

"segmentation fault: 11"

WHAT'S HAPPENED?

Thank you very much for help.

Malik.

#include <iostream>
#include <stdlib.h>
#include <assert.h>
using namespace std;
const int MAXSIZE = 10;
extern "C"
{
    void fsub(int**, int, int);
}
int main()
{
      int *A[MAXSIZE],  size;
      int  i, j, ir, jc;
      cout<<"\nRow size:";
      cin>>ir;
      cout<<"\nCol size:";
      cin>>jc;
      for( i=0;i<ir;++i)
        {
          A = new int[jc];
          assert(A != 0);
        }
      for(i=0; i<ir; ++i)
         for(j=0; j<jc; ++j)
        {
              A = 3;
          cout<<"\nA["<<i<<"]"<<"["<<j<<"]= "<<A;
        }
          cout<<endl<<"FORTRAN calling"<<endl;
          fsub(A,ir,jc);
          for(i=0; i<ir; i++)
             {
                for(j=0; j<jc; j++)
                cout<<"A["<<i<<"]["<<j<<"]="<<A<<endl;
             }
        delete[] *A;
  return EXIT_SUCCESS;
}

FORTRAN SIDE,

 SUBROUTINE FSUB(A, ROWS, COLS)BIND(C,name="fsub")
 USE, INTRINSIC :: ISO_C_BINDING
 IMPLICIT NONE
 INTEGER(KIND=C_INT), INTENT(IN), VALUE :: ROWS, COLS
 INTEGER(KIND=C_INT), INTENT(INOUT)       :: A(10,COLS)
 INTEGER                                                           :: I, J
 A=TRANSPOSE(A)
 DO I =1, ROWS
     DO J = 1, COLS
         A(I,J) = A(I,J)*100;
     ENDDO    
 ENDDO   
 END

 

 

0 Kudos
3 Replies
Highlighted
Black Belt
6 Views

Fortran multidimensional

Fortran multidimensional arrays aren't implemented with multiple layers of pointers. They are equivalent to plain c "arrays" where indexing involves calculating the offsets f2c style (almost trivial to accomplish with macro).
0 Kudos
Highlighted
6 Views

On the C/C++ side, allocate

On the C/C++ side, allocate the total amount of data in one allocation:

int* blob = new int[ir*jc];
assert(blob!=0);
for(int i=0;i<ir;++i)
   A = &blob[i*jc];
...

The A array of int* is available to C++, the call to Fortran would pass the base (blob) and the two dimensions ir and jc. Fortran would then construct the appropriate array descriptor from the dummy arguments.

Jim Dempsey

0 Kudos
Highlighted
Beginner
6 Views

Thank you both, Tim and Jim!

Thank you both, Tim and Jim!

I'm understand that interchanging arrays with the CPP and FORTRAN can be allowed via a 'flat' arrays only. :(

Malik.

PS. I has programmed in Symantec C++(Zortec C++) many years ago. Symantec C++ was supported by NCEG (Numerical C Extension Group)

There was an extern "FORTRAN" name conversions, instead the extern "C" above.

 

0 Kudos