[Rd] Fortran DLLs and R

Duncan Murdoch murdoch at stats.uwo.ca
Wed Mar 24 19:05:09 CET 2010

On 24/03/2010 1:29 PM, jferrari at umces.edu wrote:
> Hi All,
> I'm writing R code that would benefit from doing certain tasks using
> compiled blocks of code, specifically Fortran subroutines of my own
> (already written, debugged in both Fortran77 and Fortran90).
> I am currently working on a Windows machine using Lahey and/or MinGW(g77)
> compilers.
> It is possible to dynamically load Fortran DLLs into R as evidenced from
> the several documents I've found on-line giving details on how to do this
> (specifically for Windows).  However, following the examples in these
> documents... none of them successfully deliver a DLL that can be called
> from R (and I'm talking for simple test Fortran subroutines that add 2+2).
> Either the directions for creating the DLL (for a specific compiler) do
> not work (no DLL created), or a DLL is created and exists but will not be
> loaded/recognized by R (result of is.loaded = FALSE).
> Can anyone give me a quick/dirty step by step on how to create a DLL
> (using g77 compiler, specifically MinGW for Windows) so that it will work
> in R, on a Windows machine (as well as any tips on anything that has to be
> done to, or in, R to get it to work), or if there's a definitive easy to
> read paper/book describing the process?

Here's a very simple example using MinGW.  The source code in test.f:

      subroutine testfun(x, y, z)
      real*8 x, y, z
      z = x + y

Compile it using

Rcmd SHLIB test.f

which automatically executes

gfortran     -O3  -c test.f -o test.o
gcc -shared -s -static-libgcc -o test.dll tmp.def test.o -lgfortran 
-Lf:/R/svn/r-devel/R/bin -lR

(Paths will be different for you.)

Then, in R,

 > dyn.load("test.dll")
 > is.loaded("testfun")
[1] TRUE
 > .Fortran("testfun", x=as.numeric(2), y=as.numeric(2), z=as.numeric(0))
[1] 2

[1] 2

[1] 4

Duncan Murdoch

More information about the R-devel mailing list