Question: How can I write C++ code that defines classes, and make corresponding objects accesible to R?
Answer: Here is an example (file oo.cpp). I assume the Borland compiler, but it should be easy to change to your C(++) development environment.
class X { public: int n; }; static X x; extern "C" __declspec(dllexport) void setX(int * a) { x.n = *a; }; extern "C" __declspec(dllexport) void getX(int * a) { *a = x.n; };
This C++ code defines a class X, declares a static instance x of that class, and the wrapper functions getX and setX make the object accesible to R.
Here is the associated makefile (oo.mak)
oo.dll: oo.cpp bcc32 -tWD oo.cpp
To recap, the -tWD switch tells bcc32 to produce a DLL for output.
Here is the R side of the interface: (file oo.r)
# MAKE the dll, and load it if(is.loaded("_getX")) dyn.unload("oo.dll") shell("make -foo.mak") dyn.load("oo.dll") # Define wrapper functions setX <- function(a) { .C("_setX",as.integer(a)) return() } getX <- function() { .C("_getX",as.integer(0))[[1]] } print(getX()) print(setX(42)) print(getX())