From murdoch at stats.uwo.ca  Sat Feb 26 22:21:11 2005
From: murdoch at stats.uwo.ca (Duncan Murdoch)
Date: Sat Feb 26 22:21:28 2005
Subject: [Rd] calling an R-function from C
In-Reply-To: <4220D1E0.2020800@abo.fi>
References: <4220D1E0.2020800@abo.fi>
Message-ID: <kto121th1o42cj77gn9k2el3q3c0n7eil5@4ax.com>

On Sat, 26 Feb 2005 21:45:36 +0200, Ralf ?stermark <rosterma@abo.fi>
wrote :

>Hi,
>
>I would like to invoke an R-function from a program written in ANSI C. 

This is really more involved than you think.  Your program needs to
initialize the R environment, and be prepared to handle all sorts of
things (e.g. what if the R code wants to print something?)

The example you give won't work.  Section 4.7 of the 2.0.1 manual is
about C functions that are called from R.  Writing your own R
front-end is described in chapter 7 of that manual.

>Assume that I have written an R script "myRexample" and I want to invoke 
>it from C. I assume that my R script loads its data from a datafile so 
>no arguments need to be passed between my C program and R. Following 
>R-exts.pdf  (section 4.7), I write the following main:
>
>#include "my.h"                            /* includes all standard 
>h-files */
>#include <R.h>                            /* according to R-exts.pdf */
>#include <Rinternals.h>
>SEXP myRexample();
>int main(int argc,char **argv) {
>.External("myRexample");             /* invoking my R script */

.External is an R function to call external code; it's not a C
function to call R code.

>exit(0);
>}  /* end of main() */
>
>Is this a correct interpretation, given that R is properly installed in 
>the (unix) main frame?
>I'm grateful for any advice on how to proceed.

My advice would be to write your C code to be called from R; it's much
easier.

Duncan Murdoch


[Rd] calling an R-function from C
Duncan Murdoch