[Rd] C++ <-> R mapping

Ali - saveez at hotmail.com
Tue Apr 26 23:55:17 CEST 2005


>Hi Ali.
>
>  Can you post an example of some of the C++ classes and the
>style of interface you want to the methods and fields?
>It would help to make the responses concrete.
>
>  D.

Hi Duncan,

First of all, if you have not received my reply to your question, it's 
likely that the message was eaten by your spam filter.

Here is a *rough* example of the wrapper design I am currently using.

Assume we have some c++ class like:

---------------------
c++
---------------------
class foo
{
	public:
		Foo();
		void function1() { /* implementation */};
};

Now the first thing to consider before jumping to R is that R really can 
call compiled codes only from C (and Fortran). So we need some C layer like:

---------------------
c wrapper layer
---------------------
extern "C" SEXP R_Foo_New()
{
	/* return an instance of Foo as SEXP */
}

extern "C" SEXP R_Foo_function1(SEXP obj)
{
	obj->function1();

	return R_NilValue;
}

And finally we can enter to the R environment by something like:

---------------------
R wrapper layer: S4 style
---------------------
setClass("Foo",
    representation(.ptr = "externalptr"),
    );

setMethod("initialize", "Foo",
	function(.Object) {.Object at .ptr = .Call("R_Foo_New"); .Object;})

if( !isGeneric("function1") ){
    setGeneric("function1", function(.Object, ...) 
standardGeneric("function1"))
}

setMethod(
    "function1",
    signature(.Object = "Foo"),
    function(.Object, ...)
    {
        ret <- .Call("R_Foo_function1", .Object at .ptr);
        ret;
    });


The R layer approach in this example is in S4 style. Obviously, it can be 
done in S3 as well. Even it is possible to have more than one R layer 
co-existing at the same time so that the usercan help himself/herself with 
whatever choice he/she is happy with.

I have to say I am a bit surprised that in R there is no unique and standard 
class-oriented structure. In addition, as Tony Plate and Duncan Murdoch 
explained, currently, the existing designs cannot handle loads of methods.

It seems that the above gap can only be filled with some new developments. I 
am very keen to know about your approach in interfacing R to class-oriented 
languages.



More information about the R-devel mailing list