Skip to content

How to call R functions from a C++ program

2 messages · Ramon Diaz-Uriarte, Brian Ripley

#
If you want to call certain functions, such as the random number generators,
that is easy. Get the sources, untar, and ./configure; then go to standalone
src/nmath/standalone, and read the README; if you want to call them as static
libraries, type make archive.  That will create the libRmath.a library.

Now, if you were using C, that would be all. But to use those functions from a
C++ program you need to modify Mathlib.h (in R_DIRECTORY/src/include/R_ext). 
Edit Mathlib.h and insert, before any of the function headers,

extern "C" {

(don't forget to add also the closing braket at the end of the file).
(The reason why you need to do this is explained, for instance, in Meyer's
"More effective C++", itme 34).

Thats it; you can now use the functions in Mathlib.h by giving the appropriate
paths to the library and header files.

For instance:

g++ -I/usr/lib/R-patched/src/include -L/usr/lib/R-patched/src/nmath/standalone
test1.cc -lRmath -lm



Ramon
On Fri, 03 Nov 2000, Nathapong Samlamjiag wrote:
#
On Fri, 3 Nov 2000, Ramon Diaz-Uriarte wrote:

            
(BTW, I had spotted that a couple of days ago for linking C++ code
into R, and we will modify the header files. Until then, I suggest using

extern "C" {
#include "R_ext/Mathlib.h"
}

rather than edit the headers.)
But that does not call R functions from a C++ program, just a few
utilities in R.  I read `R functions' as the interpreted ones like lm.

The short answer is that you cannot easily do this yet.  On Windows
you can embed R or use a DCOM link.  On Unix similar things (building
R as a shared library, CORBA connections) are in various stages of
preparation.  In all of these you need to remember that R expects
to run its own event loop, and that can cause contortions: this is never
going to be straightforward.

You may have more success calling R functions from a C++ package 
running under R, using eval in a .Call for example.