From reid_huntsinger at merck.com  Tue Jun 14 19:32:21 2005
From: reid_huntsinger at merck.com (Huntsinger, Reid)
Date: Tue, 14 Jun 2005 13:32:21 -0400
Subject: [Rd] Calling C from Fortran
Message-ID: <D9A95B4B7B20354992E165EEADA31999056A948E@uswpmx00.merck.com>

The C wrappers are there to align the linking conventions expected by the
Fortran compiler (usually subroutine/function foo has its entry point in the
object file indicated by a symbol foo_, but it depends on the platform) to
that of the C compiler. (The C compiler just uses the function name.) The
wrappers give C functions named whatever is appropriate (eg "foo_") to get
an entry point that "call foo" will trigger linking to. 

Calling the Fortran subroutine from R is via .Fortran() after doing a
dyn.load() of the shared object file. Creating the shared object should just
be a matter of R CMD SHLIB file1.c file2.f but I've never tried using
Fortran and C together. Take a look at the magic built in to the R CMD SHLIB
and R CMD COMPILE commands, and at some of the packages that come with R (I
just do a "find" for "*.f" in the src tree) if you need examples, eg.
src/library/stats. 

Reid Huntsinger

-----Original Message-----
From: r-devel-bounces at r-project.org [mailto:r-devel-bounces at r-project.org]
On Behalf Of Gilles GUILLOT
Sent: Tuesday, June 14, 2005 1:05 PM
To: R-devel at stat.math.ethz.ch
Subject: [Rd] Calling C from Fortran


I would like to call C routines from Fortran under linux as suggested in 
section 5.6 of 
the "Writing R extensions" documentation.

I'm familiar with Fortran but not with C.
I understand the example provided in Fortran:

subroutine testit()
double precision normrnd, x
call rndstart()
x = normrnd()
call dblepr("X was", 5, x, 1)
call rndend()
end


but I don't understand the purpose of this C wrapper:
#include <R.h>  
 void F77_SUB(rndstart)(void) { GetRNGstate(); }
 void F77_SUB(rndend)(void) { PutRNGstate(); }
 double F77_SUB(normrnd)(void) { return norm_rand(); }

neither how I should compile it.

Could anyone explain how I should compile and link 
the C and Fortran files above, and call the Fortran subroutine from R.

Thanks,

Gilles

______________________________________________
R-devel at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] Calling C from Fortran
Huntsinger, Reid