c++fortranoptional-parametersfortran-iso-c-binding

Calling Fortran subroutines with optional arguments from C++


How would I reference a Fortran function in a C++ header that uses optional arguments? Would I have a prototype in the header for each possible combination of calls? Or is this even possible?

For instance, Fortran:

subroutine foo(a, b, c) bind(c)
   real, intent(in), optional :: a, b, c
   ...
end subroutine foo

Solution

  • It is not possible, at least portably, unless you make the subroutine bind(C).

    Once you make it bind(C), it is just passing of a pointer which can be NULL on the C side.

    subroutine foo(a, b, c) bind(C, name="foo")
       use iso_c_binding, only: c_float
       real(c_float), intent(in), optional :: a, b, c
       ...
    end subroutine foo
    

    (for greater portability I used real(c_float) from the iso_c_binding module, but that is somewhat tangential to this question)

    In C(++)

    extern "C"{
      void foo(float *a, float *b, float *c);
    }
    
    foo(&local_a, NULL, NULL);
    

    and then you can make a C++ function which calls foo and which employs C++-style optional parameters.

    This capability was allowed in Fortran in Technical Specification ISO/IEC TS 29113:2012 on further interoperability of Fortran with C and was later incorporated into Fortran 2018.