<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">\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 &lt;iostream.h&gt;
#include "X.hh"

static Y y;

X::X()
{
  cout &lt;&lt; "constructor X" &lt;&lt; endl;
}

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

Y::Y()
{
  cout &lt;&lt; "constructor Y" &lt;&lt; endl;
}

Y::~Y()
{
  cout &lt;&lt; "destructor Y" &lt;&lt; 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.

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



</pre></body></html>