Skip to content

pass by reference for S4

2 messages · Biczok Rudolf, Martin Morgan

3 days later
#
"Biczok Rudolf" <r.biczok at dkfz-heidelberg.de> writes:
R has the notion of an external pointer, which is a pointer to C-level
data. Is that what you mean? See ?"externalptr-class" and the 'Writing
R Extensions' manual for details.

More likely you mean that you want to pass references rather than
values. An approach is to create an environment and place objects in
it; environments have pass-by-reference semantics.

  env <- new.env(parent=emptyenv())
  env$myobj <- ...

Environments can be placed in slots of an S4 class, so the contents of
instances of the class will not be copied. You have to pay attention
when creating the S4 instance that each instance gets a new
environment, e.g., defining an 'initialize' method or a class
constructor.

 setClass("MyClass", representation=representation(env="environment"))
 setMethod("initialize", "MyClass", function(.Object, myData, ...) {
     env <- new.env(parent=emptyenv())
     env$myData <- myData
     callNextMethod(.Object, env=env, ...)
 })

and then
[1]  1  2  3  4  5  6  7  8  9 10

R users will be confused by pass-by-reference semantics.  Others might
point you to the R.oo or proto packages.

Martin