Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Fortran/C++ pointers

maksyutov__malik
Beginner
721 Views

Hello!

There is some main C++ code that will calling a fortran subroutine,

#include <cstdlib>
#include <iostream>
using namespace std;
/*
 *  Fortran/C++ interoperability
 */
extern "C" void Fortran_f(double**, int);
int main()
{
    int i, sz =10;
    double **AG;
    AG=new double*[sz];
    for (i=0;i<sz;i++)AG=(double*)malloc(sizeof(double));
//
//  Do something with AG
//    
    Fortran_f(AG,sz);
    return EXIT_SUCCESS;
}

C-function "malloc" for the reallocation purposes in C++ main was using(however, will be provided by the fortran function later).

How to pass AG object to the Fortran function?

My first try is,

SUBROUTINE FORTRAN_F(PAG,SZ)BIND(C,name="Fortran_f")

USE, INTRINSIC :: ISO_C_BINDING

IMPLICIT NONE
TYPE(C_PTR)     :: PAG 

INTEGER, INTENT(IN), VALUE :: SZ
TYPE PRV
      DOUBLE PRECISION, POINTER :: PA(:)
END TYPE

INTEGER                                                  :: I, J, M, N

DOUBLE PRECISION.                             :: X
TYPE(PRV)                                               :: P_PAG
TYPE(PRV),POINTER,DIMENSION( : )   :: AG
TYPE(C_PTR), POINTER                        :: CPAG

CALL C_F_POINTER(PAG,CPAG)

ALLOCATE(AG(SZ))

DO I = 1, SZ

          CALL C_F_POINTER(CPAG,AG(I)%PA)

ENDDO

!

!  Do something in Fortran code

!           AG  =>REALLOCATE(AG, new_size) ! My own realloc function

.................

DO I = 1, M

      DO J = 1, N

            AG(I)%PA(J)=AG(I)%PA(J)+SIN(X)

      ENDDO

ENDDO

...........

END SUBROUTINE.

Unfortunately, it didn't work with the following error: 

  forrtl: severe (408): fort: (7): Attempt to use pointer PA when it is not associated with a target

WHAT'S WRONG?

 

 

0 Kudos
3 Replies
jimdempseyatthecove
Honored Contributor III
721 Views

Only one of the languages should perform the allocations, reallocations and deallocations of objects.

Look at the documentation for the C interoperability features, in particular the means to use/pass Fortran descriptors to C/C++ programs.

As an additional note.

Fortran uses descriptors into an allocatable array that is contiguous. IOW this is not an array of pointers to rows of data.

In C/C++ it is more efficient to allocate a 2D array as a 1D array, possibly sticking the pointer into the C/C++ pointer[0] of the row table, then populate the row table for each stride into the blob that constitutes the 2D array.

Jim Dempsey

0 Kudos
maksyutov__malik
Beginner
721 Views

Many Thanks Jim!

0 Kudos
Reply