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}\bigskipSuppose 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 functionand ensure that the function(s) containing symbols we want to callfrom 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.ccg++ -c X_wrap.ccg++ -shared -o X.so X_wrap.o X.o\end{verbatim}Otherwise \verb+__main()+ and hence the constructor of the staticvariable \verb+Y+ may not be not called. (Replace \verb+-shared+ by\verb+${SHLIBLDFLAGS}+ from \verb+R_HOME/etc/Makeconf+ on other Unixplatforms; on Windows add the library \verb|-lstdc++|.)Now starting R yields\begin{verbatim}R : Copyright 1999, The R Development Core TeamVersion 0.65.0 (August 27, 1999)...Type "q()" to quit R.> dyn.load("X.so")constructor Y>.C("X_wrap")constructor Xdestructor Xlist()> q()Save workspace image? [y/n/c]: ydestructor Y\end{verbatim}