Pass arrays from C/C++ to Fortran and return a calculated array

后端 未结 2 1788
眼角桃花
眼角桃花 2020-12-03 18:51

I am trying to pass an array from C/C++ into a Fortran 2003 module and get the calculated values back into C/C++. I\'ve been able to pass and return single values (scalars)

2条回答
  •  感情败类
    2020-12-03 19:01

    Before francescalus confirms it, I was going to say that from what I know that was a little bit old, the interoperability does not permit what you are trying to do with arrays. In addition, some good habits are always critical when coding. For example using implicit none in fortran to force the declaration of all variables before they are used. The use of named constant when the language permits it, for example the 2 that you are using as array size in fortran.

    Below is a modified version of your code that should do something like what you want to achieve.

    //Fortran

    module ConvertUnitsLib
    
    use :: iso_c_binding ! for C/C++ interop
    !real(c_double), bind(c) :: degF, degC
    implicit none
    
    public DegCtoF
    
    contains
    
    !
    ! Convert temperature degrees Celsius Fahrenheit
    !
    subroutine DegCtoF(degC, degF, n)&
        bind(c, name = "DegCtoF")
    
        integer, intent(in) :: n
        real(c_double), intent(in), dimension(n) :: degC
        real(c_double), intent(out), dimension(n) :: degF
        integer :: i
    
        do i = 1, n
            degF(i) = ( degC(i) * 1.8 ) + 32
        end do
    
    end subroutine DegCtoF
    

    // C++

    #include 
    
    #ifdef __cplusplus
    extern"C" {
        #endif
        double DegCtoF(double [], double [], const int *);
        #ifdef __cplusplus
    }
    #endif
    
    
    /**********************************************************************/
    
    
    int main(int argc, char *argv[])
    {
        const int N = 2;
        printf("C/C++ and Fortran together!\n");
    
        double DegreesC[N] = {32, 64};
        double DegreesF[N];
    
        DegCtoF(DegreesC, DegreesF, &N);
        for(int i = 0; i

提交回复
热议问题