The R Project SVN R

Rev

Rev 6098 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

\section{Dynamically loading a C++ library from R}

\noindent
\emph{Adrian Trapletti}

\bigskip
Suppose we have the following hypothetical C++ library, consisting of the two files
\verb+X.hh+ and \verb+X.cc+, which we want to use in R:
\begin{verbatim}
-------------------------------
X.hh
-------------------------------
class X
{
public:
  X ();
  ~X ();
};

class Y
{
public:
  Y ();
  ~Y ();
};
-------------------------------
X.cc:
-------------------------------
#include <iostream.h>
#include "X.hh"

static Y y;

X::X()
{
  cout << "constructor X" << endl;
}

X::~X()
{
  cout << "destructor X" << endl;
}

Y::Y()
{
  cout << "constructor Y" << endl;
}

Y::~Y()
{
  cout << "destructor Y" << endl;
}
\end{verbatim}
implementing the 2 classes \texttt{X} and \texttt{Y}. 
The only thing we have to do is to write a wrapper function 
and ensure that the function(s) containing symbols we want to call
from R are bracketed by 
\begin{verbatim}
extern "C" {

}
\end{verbatim}
For example, 
\begin{verbatim}
-------------------------------
X_wrap.cc:
-------------------------------
#include "X.hh"

extern "C" {

void X_wrap ()
{
  X x;
}

}
\end{verbatim}
Compiling and linking should be done with the C++ compiler-linker,
for example under Linux
\begin{verbatim}
g++ -c X.cc
g++ -c X_wrap.cc
g++ -shared -o X.so X_wrap.o X.o
\end{verbatim}
Otherwise \verb+__main()+ and hence the constructor of the static
variable \verb+Y+ may not be not called.  (Replace \verb+-shared+ by
\verb+${SHLIBLDFLAGS}+ from \verb+R_HOME/etc/Makeconf+ on other Unix
platforms; on Windows add the library \verb|-lstdc++|.)


Now starting R yields
\begin{verbatim}
R : Copyright 1999, The R Development Core Team
Version 0.65.0  (August 27, 1999)
...
Type    "q()" to quit R.

> dyn.load("X.so")
constructor Y
>.C("X_wrap")
constructor X
destructor X
list()
> q()
Save workspace image? [y/n/c]: y
destructor Y
\end{verbatim}