Fortran + Julia

I have something in Fortran like this:

  • subroutine METHOD in file method.f calling subroutine eval;
  • subroutine EVAL in main.f;
  • program MAIN calling METHOD, also in main.f.

I can easily call METHOD from Julia with ccall, but can I define the subroutine eval from Julia?

In order to access a Fortran routine from Julia using ccall, the Fortran routine needs to be available in a shared library—see the documentation. Could you copy your EVAL function into a new file and then compile it into a library? That would seem to me to be the simplest solution.

Sorry, I wasn’t clear.

I want to implement the subroutine EVAL in Julia, so that the Fortran METHOD calls that one.

Furthermore, I want to call METHOD from Julia using ccall, but this last part I can do.

In other words, I want to call a Julia function from a Fortran subroutine called from a Julia function.

Oh, I see. I misunderstood. I’ve never tried to call Julia code from another language but it certainly seems to be possible. As far as I can tell from the Embedding Julia page of the documentation, there is a C API that allows calling Julia functions from C. It seems like you need to create a C function that calls your Julia function then use Fortran’s ability to call C functions.

Thanks, that might work.

Fortran supports C function pointers, so you might be able do this using cfunction and avoid the C wrapper if you want.

(This would be neat to have as an example, so please post either way if you get something running!)

1 Like

I think that would require me changing the METHOD code, and that’s not available.
If I make it, I’ll make a post. :+1:

I know its been a while since you posted, but did you manage to make it work? I am trying to call a FORTRAN subroutine from Julia, where one of the arguments would be a Julia function. I could not find a dummy example online. It would be great to have a simple working example for that.

I’m afraid not. Calling things in Fortran has been reasonably simple, but I didn’t manage to have Fortran call things in Julia. But I haven’t touched that since Julia 0.6 or 0.5. Maybe you’ll have more luck.

julia> fname = tempname() * ".f90"

julia> open(fname,"w") do f
           write(f,"subroutine hello(x,z,y)\n")
           write(f,"    real*8 x,y\n")
           write(f,"""    print *, "Hello World! ", x,y, " testing"\n""")
           write(f,"end subroutine hello\n")

julia> run(`gfortran -shared -fPIC -o $fname`)
Process(`gfortran -shared -fPIC -o /tmp/juliaxmqlRU.f90`, ProcessExited(0))

julia> tt = 23.; uu = 12.;

julia> t = ccall( (:hello_, "./libhello"), Int64, (Ptr{Float64},Ptr{Nothing},Ptr{Float64}),Ref(tt),[],Ref(uu))
 Hello World!    23.000000000000000        12.000000000000000       testing