A program is supposed to be linked as an executable, so you can't call it from a subroutine - or you call the executable (with SYSTEM in gfortran), but you could do that directly from R.
The easy way to call Fortran from R is the .Fortran R function, which calls a Fortran subroutine
(not a function
, nor a program
).
The basic steps are :
- compile a Fortran DLL, exporting the subroutines you need (of course they may be wrappers for other subroutines or functions)
- put the DLL in a directory in your system path
- from R, load the DLL with dyn.load
- call your subroutine with
.Fortran
.
If you use gfortran, you may just install Rtools, which has everything you need. If you want to use another compiler, you may have some trouble, especially with names.
From your comment to user2188538's answer, I see you already know all these steps, but be very careful with symbol names. From the .Fortran
help: Use .Fortran with care for compiled Fortran 9x code: it may not work if the Fortran 9x compiler used differs from the Fortran 77 compiler used when configuring R, especially if the subroutine name is not lower-case or includes an underscore. It is also possible to use .C and do any necessary symbol-name translation yourself.
Also, I suspect your wrapper subroutine should not reside inside a module, or you may have extra trouble with names. But this is only a limitation for the wrapper function, which must be visible from R.
You can check the exported names in your DLL (send objdump -x your.so
to a file and look for exported symbols). And check also in R, with is.loaded("your.symbol")
, after loading the DLL. Be aware that usually, gfortran appends an extra underscore to names, whereas it's not needed when you call .Fortran
from R. As described above, you may use .C
instead (but then, remember Fortran arguments are passed by reference).
To check that you understand the whole process, I suggest you test it on a trivial example, such as a unique subroutine mysub(x,y,z)
that does only z=x+y
. When this one runs, you can elaborate on it to call more complex routines.
edit You should not use assumed-shape or deferred-shape arrays, when you pass arrays arguments from R to Fortran, but only assumed-size arrays, that is, the usual array passing in Fortran 77. This is because R knows only how to pass a pointer to raw data, whereas assumed-shape and deferred-shape need more information, and R does not know the data structure to do that.
For example, you can do that:
subroutine mysub(n, a)
real :: a(n, n)
...
end subroutine
But this will amost certainly fail:
subroutine mysub(a)
real :: a(:, :)
...
end subroutine
Also, you can't pass function arguments from R to Fortran, as that would need a special data structure for the callback (under the hood, R is a Scheme dialect, and it uses S-expressions). You may do that in C, through .C
or .Call
(see help for .Call and R Internals).