Fortran calling convention when passing an array with unknown size

In modern Fortran when an array is passed to a subroutine, we don’t really need to specify its size: the size can be read from size(arr). So the follows

    function my_length(arr) 
        real(8), intent(in), dimension(:) :: arr
        integer :: my_length 

        my_length = size(arr) 
    end function my_length


Now suppose I’m going to pass a Julia array to some Fortran code, and definitely the latter needs to know the size of the array. If I naively compile the Fortran my_length into a so file, then then call the function in that so file from Julia, then that’s what I get:

arr = [1.0, 2.0, 3.0]
res = @ccall "./".my_length_(arr::Ptr{Float64})::Int32

So since the Julia vector is passed to my_length_ as a pointer, the length information expectedly is not received by my_length_.

What makes me curious then is how the size of the array is passed to my_length when the latter is called from Fortran, or in other words, what exactly is the calling convention of a Fortran function accepting an array with unknown size: is the size being passed to the function as a hidden argument, or something else? If so is it possible to not explicitly declare a size argument in the Fortran part of the code, and do

@ccall "./".my_length_(arr::Ptr{Float64}, 
arr_size::Ref{Int32} # Argument not explicitly declared in the Fortran code but still there

at the Julia side?

I don’t know if there is a standard concering this or it’s compiler dependent.

Such a Fortran routine requires that you provide the array argument in the form of an “array descriptor” which is a compiler-dependent data structure. If you’re curious about these, search for information about ISO_Fortran_binding (which allows C code to call modern Fortran).

1 Like

Yeah I realized the problem is not really about Julia, but about how to call Fortran from C (and @ccall follows the C convention). There is also a stack exchange question about that: Fortran90 and size of arrays created in C++ - Stack Overflow.

It will be very helpful if someone can make a @fcall macro to make calling Fortran subroutine slightly easier…