the run time aborting when calling c++ sub from fortran

后端 未结 1 1779
旧巷少年郎
旧巷少年郎 2021-01-07 08:29

I had read many posts here about mixing languages use of Fortran and C++. However, I\'m still stuck with my current problem: my Fortran program always aborted.


1条回答
  •  伪装坚强ぢ
    2021-01-07 08:52

    You use the iso_c_binding module, but your procedure interface is not C interoperable.

    The iso_c_binding module is not the most important thing. The bind(C) attribute is the key. (I ranted several times about the unfortunate name of the tag here)

    You use an assumed shape allocatable array argument

    real(c_float),allocatable::rh(:,:,:)
    

    these are not allowed in interoperable procedures in Fortran 2008, because C or C++ have no idea what to do with them. They are not just addresses. If you used the bind(C) attribute in the interface, the compiler should tell you it is wrong.

    There is a possibility to pass them in the next Fortran standard (in an existing TS actually) using a special C header, but some compilers (notably gfortran) are still not compatible.

    As you do not do any reallocation on the C side (at least in your example), you can just pass the array as an assumed size (array(*)) argument. I also changed the C++ name, no need for the underscore.

    interface
      subroutine  deb_cc(rh,x,y,z_ext) bind(C, name="deb_cc")
        use ISO_C_BINDING
        real(c_float) :: rh(*)
        integer(c_int):: x,y,z_ext
       end subroutine
    end interface
    

    On the C side, you cannot use the C arrays which are pointers to pointers ([i][j][k]). What you receive from Fortran is a single block of memory. You also have to pass the array shape. At least in the first two Fortan dimensions.

    I would just use a macro to index the array in C.

    // adjust as needed, many variants possible
    #define IND(i,j,k) = i + (j-1) * nx + (k-1) * nx * ny
    // adjust as needed, many variants possible
    
    
    extern "C" void deb_cc(float *rh, int *nx, int *ny, int *nz) {
      cout <<"thinktest i=8,j=4,k=1"<< " x3/rh " << rh(IND(8,4,1))<

    0 讨论(0)
提交回复
热议问题