[Rcpp-devel] returning array from C

Krzysztof Sakrejda krzysztof.sakrejda at gmail.com
Tue Jun 11 20:36:47 CEST 2013


On Tue, Jun 11, 2013 at 2:12 PM, Steve Jaffe <sjaffe at riskspan.com> wrote:
>> You can get what you want, but you'll have to use XPtr, then on the R side
>> write a reference class and methods which make the object behave like a
>> numeric vector.  No copying necessary.
>
>
> This did occur to me, and I looked to 'ff' as an example, but haven't dug
> into it deeply enough to be clear about the details.
>
>
>
> Would you know of a simple example of writing a "reference class" that looks
> to R like a numeric vector?

I think all the examples I've written are too complicated to be useful
but as a simple example break it into two problems, first ignore the
Rcpp side and write everything for a ref class which just has a vector
as a member:


setRefClass(
  Class = "notAVector",
  fields = list(
    avector = "numeric"
  ),
  methods = list(
    initialize = function(x) { avector <<- x },
    add = function(y) { avector <<- avector + y; return(avector) },
    sub = function(y) { avector <<- avector - y; return(avector) }
  )
)

setMethod(
  f="[",
  signature = signature(x='notAVector', i='numeric', j='missing'),
  definition = function(x, i) {
    return(x$avector[i])
  }
)

setMethod(
  f="[<-",
  signature = signature(x='notAVector', i='numeric', j='missing',
value='numeric'),
  definition = function(x, i, value) {
    x$avector[i] <- value
    return(x)
  }
)

setMethod(
  f="+",
  signature = signature(e1='notAVector', e2='numeric'),
  definition = function(e1,e2) return(e1$add(e2))
)


setMethod(
  f="+",
  signature = signature(e1='numeric', e2='notAVector'),
  definition = function(e1,e2) return(e2 + e1)
)

Then all you have to do is replace the numeric vector member with an
"externalptr" member which is an XPtr on the Rcpp side, and implement
the operations for the methods.  It's a lot of code but the result is
pretty nice.  I'm doing similar things for some code which is part of
my dissertation, but I haven't put the Rcpp/R part of it anywhere
public yet.

Krzysztof



--

Krzysztof Sakrejda

Organismic and Evolutionary Biology
University of Massachusetts, Amherst
319 Morrill Science Center South
611 N. Pleasant Street
Amherst, MA 01003

work #: 413-325-6555
email: sakrejda at cns.umass.edu
-----------------------------------------------


More information about the Rcpp-devel mailing list