[Rcpp-devel] pass-by-reference for reference objects

Greg Minshall minshall at umich.edu
Sat Mar 9 01:36:23 CET 2013

hi.  i have been trying to understand how to pass objects back and forth
by reference (in order to avoid copying).  this works smoothly if one is
calling a method on the object.  but, i was having trouble figuring this
out for "free functions" (i.e., non-member functions, i.e.,
non-methods).  the term "free function" itself i discovered in

the answer is to define a function which has the desired
pass-by-reference class as its first parameter, as a pointer, and then
list that function as a *.method* in the class_ field of the
RCPP_MODULE() call.  i.e. (see that attached for the gory details),
given a class
class space2d ...

one defines a function or two:
space2d* psps(space2d* arg, int val) {
    arg->set(1, val);
    return arg;

void vps(space2d* arg, int val) {
    arg->set(1, val);

and then does some module stuff:

using namespace Rcpp;
RCPP_MODULE(test6_module) {
        .method("psps", &psps)
        .method("vps", &vps);

in the above, changes made to arg in both psps() and vps() will be seen
by the caller.  in addition, the receiver of the return value of psps()
will *also* hold a shared copy of the reference object.


(it might be a Nice Addition to remove the limitations of only one
pass-by-reference, location in the formal parameters, etc.  someday...)

cheers, Greg
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: test6.cc
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130308/2f7b666a/attachment-0001.ksh>

More information about the Rcpp-devel mailing list