Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating Fortran code in Julia

Tags:

fortran

julia

I am using the GNU gfortran compiler (on Cygwin) for my own module. A good example will hopefully start from the compilation stage, address mangled names and call the subroutine from Julia via ccall. Most examples I've seen skip the first two stages.

So imagine that I have the following module in Fortran 90 file named 'f90tojl.f90':

module m
contains
    integer function five()
      five = 5
    end function five
end module m

This example is from here. I compile it with gfortran as follows to create a shared library:

gfortran -shared -O2 f90tojl.f90 -o -fPIC f90tojl.so

And my, admittedly shaky, understanding from reading the Julia docs suggest that I should be able to call the function five like so:

ccall( (:__m_MOD_five, "f90tojl"), Int, () )

It didn't work for me. I get 'error compiling anonymous: could not load module f90tojl.... Anyone cares to enlighten me? I got the sneaky sense I'm doing something silly....

In the official doc, the emphasis is on C. I'm also aware of this for C++. In R and Python, the momentum -- I have Cython and Rcpp in mind -- seems to be C/C++. Similar to this question, I want to get a sense of how easy it is to interface Julia with Fortran vs Julia with C/C++.

like image 675
vathymut Avatar asked Dec 16 '14 06:12

vathymut


2 Answers

Calling Fortran and C are essentially the same, as the documentation says. There are just far fewer examples because there is far less code people want to wrap, I suppose. Wrapping C is super easy in Julia, very pleasant. Its not typically done for speeding up Julia, like with R or Python, but more to take advantage of quality code already written.

Julia's standard library itself is a great example of integrating with Fortran code, e.g. here is the Julia wrapper for ARPARK. Outside of Base, glmnet is written in Fortran, and there is a Julia wrapper for it (GLMNet.jl).

I don't see how the modern Fortran distinction matters.

like image 150
IainDunning Avatar answered Nov 09 '22 11:11

IainDunning


For those who, like me, got here with the hope of a copy-paste recipe to get the hands over the matter, here is a working code (typos-corrected from http://julia-programming-language.2336112.n4.nabble.com/example-for-ccall-use-and-fortran-tp7737p7740.html).

Fortran file: simplemodule.f95

module simpleModule

contains
function foo(x)
  integer :: foo, x
  foo = x * 2
end function foo


end module simplemodule

Which has to be compiled with gfortran simplemodule.f95 -o simplemodule.so -shared -fPIC, producing the simplemodule.so shared library file.

Then, in Julia,

a = Int32[3]
ccall((:__simplemodule_MOD_foo, "./simplemodule.so"), Int32, (Ptr{Int32},), a)

returns 6.

The thread contains other examples, too.

like image 41
Gabriele Avatar answered Nov 09 '22 11:11

Gabriele