[Rcpp-devel] Calling R from C++, seeing results in C++

F.Tusell fernando.tusell at ehu.es
Fri May 23 11:12:55 CEST 2014


I have been struggling with the following:

file test4.R
============

library(Rcpp)
library(RcppArmadillo)

MyClass <- setRefClass("MyClass",
		       fields=c(
			 A="numeric"
			 ),
		       methods=c(
			 initialize = function() {
			   A <<- 1:4
			 },
			 update = function() {
			   A <<- 2*A
			 },
			 modify  = function() {
			   test4( .self$A, .self$update )
			 }
			 )
		       )

file test4.cpp
==============

// [[Rcpp::depends(RcppArmadillo)]]

#include <RcppArmadillo.h>

// [[Rcpp::export]]
int test4(Rcpp::NumericVector A, Rcpp::Function fn) {
  arma::cube aF(A.begin(), 1, 2, 2, false) ;
  Rcpp::as<Rcpp::NumericVector>( fn() ) ;
  Rcpp::Rcout << "aF =  " << aF << std::endl;
}


When I source these files, I can execute:

> MyObj   <- MyClass$new()

> MyObj
Reference class object of class "MyClass"
Field "A":
[1] 1 2 3 4

> MyObj$modify()
aF =  [cube slice 0]
   1.0000   2.0000

[cube slice 1]
   3.0000   4.0000


[1] 0

> MyObj$A
[1] 2 4 6 8

The intent was to overlay miobj$A with the Armadillo cube aF within
C++ function test4, so that changes in miobj$A triggered by calling
miobj$update (vía fn() inside test4) would be seen in aF.

However, this is not the case: miobj$A is multiplied by 2, as it
should, but aF remains unaltered. One of the problems (perhaps not the
only one) is that miobj$A keeps changing place whenever is assigned (I
was using a reference class in the hope that the memory used by objects
would not change).

So the question is: Is there a way to invoke from a C++ function an R
function which modifies an R object, and see the results reflected in a
C++
object immediately, without copying?

Grateful for any hints or leads on where to look. Best, ft.




More information about the Rcpp-devel mailing list