fortran pass character*81 array to c/c++ code

前端 未结 2 2056
独厮守ぢ
独厮守ぢ 2021-01-28 09:58

I am a fresh in programming, I wanna to call a fortran function in my c++ code. the thing is I dont know how to pass a fortran character*81 array to my c++.

fortran code

2条回答
  •  广开言路
    2021-01-28 10:42

    The following code seems to work for gcc4 on Linux(x86_64), but it is not clear whether it is also valid for other platforms. (As suggested above, C-interoperability of modern Fortran may be useful.)

    func01.f90

    subroutine func01( a )
        character(*) :: a( 2 )
        print *
        print *, "char length = ", len(a(1)), len(a(2))
        print *, "raw a(1) : [", a(1), "]"
        print *, "raw a(2) : [", a(2), "]"
        print *, "trim     : [", trim(a(1)), "] [", trim(a(2)), "]"
    end
    

    main.cpp

    extern "C" {
        void func01_( char *c, const int len );
    }
    
    #include 
    #include   // for memset()
    int main()
    {
        const int lenmax = 30, numstr = 3; // changed char length to 30 to fit in the terminal
        char a[ numstr ][ lenmax ];
        std::string str[ numstr ];
    
        str[0] = "moon"; str[1] = "mercury"; str[2] = "jupiter";
    
        for( int k = 0; k < numstr; k++ ) {
            memset( a[k], ' ', lenmax );  // fill space                                              
            str[k].copy( a[k], lenmax );  // copy at most lenmax char (no \0 attached)                        
        }
    
        func01_( a[0], lenmax );
        func01_( a[1], lenmax ); // pass from mercury
        return 0;
    }
    

    Compile

    $ g++ func01.f90 main.cpp -lgfortran
    

    Result

    char length =           30          30
    raw a(1) : [moon                          ]
    raw a(2) : [mercury                       ]
    trim     : [moon] [mercury]
    
    char length =           30          30
    raw a(1) : [mercury                       ]
    raw a(2) : [jupiter                       ]
    trim     : [mercury] [jupiter]
    

提交回复
热议问题