Calling a C function from Fortran where the C function name was originally passed in from C

后端 未结 2 955
谎友^
谎友^ 2021-01-22 14:42

For reasons that are not relevant, I need to pass a C/C++ function name into a Fortran subroutine, which, in turn, calls that C function. What I have found is that I can succesf

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-22 15:31

    When passing scalar values between Fortran and C, you have basically two options:

    • You pass them by reference: On the C-side you have to make sure, that you use pointers to those scalars.

    • You pass them by value: On the Fortran side you have to make sure that you use the VALUE attribute, as already suggested by other posts.

    As for the intent(in) attribute, it can stay there, as it does not affect, whether the variable is passed by value or reference. In Fortran, arguments are always passed by reference unless you specify the VALUE attribute. The attribute intent(in) only tells the compiler to prevent a usage of that dummy argument in the routine, which would change its value.

    Additional note on the naming: You should specify your Fortran routine fortranRoutine also with bind(c). This way you can specify its name as seen from C, even if it is inside a module:

    module my_interface
      use iso_c_binding
    
    contains
    
      subroutine fortranRoutine(calledFromFortran) bind(c, name='fortranroutine')
      ...
      end subroutine fortranRoutine
    
    end module my_interface
    

    This way you can be sure, the name of the function to be called from C is fortranroutine, independent of the convention of the compiler to append underscores, prepend module names or convert names to lower case. Consequently, you would have a a header file in C, which should work compiler independently:

    extern "C" {
      void fortranroutine(void(int status));
    };
    

提交回复
热议问题