[R] Calling R from C - part way there but need a push!
m at de-minimis.co.uk
Tue Apr 29 18:19:11 CEST 2008
I've read the manual on "Writing R Extensions" and in particular the
part on calling R from C. (Most of the manual is about calling C
from R, not the other way around.)
The good news is that I can now call _some_ R from C, specifically
the R functions which have C header files. However it isn't clear to
me how to call R functions that are written in R. I imagine that
there is a standard C function of the form
Call_r_from_C("package name", "Rfunction name as a string", arg1,
where arg1 etc are standardised ways of representing R data
structures in C. However I haven't been able to find such a function
prototype in the R include/*.h files. See footnote (1). Can you
point me in the right direction please? Is there a set of examples
somewhere that I can peruse?
Does R keep any state when being called from C? Should I think of it
as being a co-process, so I can make consecutive calls to it and
expect it to remember previous calls? I'm thinking of a sequence of
calls such as "load library", "load R code from a file of my own",
"set value of x", "make a call and read the values back into my C
Help is much appreciated.
(1) The most likely include file is Rinterface.h and within that the
most likely candidates seem to be:
extern int (*ptr_R_ReadConsole)(const char *, unsigned char *, int,
extern void (*ptr_R_WriteConsole)(const char *, int);
extern void (*ptr_R_WriteConsoleEx)(const char *, int, int);
but it turns out that they assume that R is running the terminal and
these are requests to R to display or read from R's console. R isn't
acting as the back end being given work and returning answers.
(2) Googling "calling r from c" yields precisely five hits, most of
which just point back at the R extensions document with vague "It's
in there somewhere"'s. I've looked!
(3) Leads suggested by help.search("C")
Foreign Function Interface Functions to make calls to compiled
code that has been loaded into R.
.Internal(base) Call an Internal Function
'.Internal' performs a call to an internal code which is built in
to the R interpreter.
Only true R wizards should even consider using this function, and
only R developers can add to the list of internal functions.
(Definitely not me!)
.Primitive(base) Call a "Primitive" Internal Function
The advantage of '.Primitive' over '.Internal' functions is the
potential efficiency of argument passing.
(4) R code that I have called successfully is that with prototypes
defined in e.g. include/R_ext/Applic.h
More information about the R-help