简体   繁体   中英

Rcpp: Inconsistent behavior with proxy model

This post discusses some issues with the proxy model for parameter passing in Rcpp. However, when I implemented this function:

// [[Rcpp::export]]
void test_size(NumericVector test){
  NumericVector test2(test);
  NumericVector test3 = NumericVector::create(1,1,1,1,1);
  test2 = test3;
  Rf_PrintValue(test);
}

We get:

> temp = c(2,2,2,2)
> test_size(temp)
[1] 2 2 2 2

So the problem is that the previous post and this book say that in this case test2 should be a pointer to the underlying SEXP object from R . However, when we assigned test2 = test3 , this didn't apply to test because the test NumericVector remained unchanged.

updated

I am adding an example where I think assignment isn't working as Dirk suggested, but of course I could be misunderstanding the problem.

So suppose I have the following function:

// [[Rcpp::export]]
NumericVector testing(){
  NumericMatrix mat(3,3);
  mat.row(0) = NumericVector::create(1,1,1);
  mat.row(1) = NumericVector::create(1,1,1);
  mat.row(2) = NumericVector::create(2,2,2);
  NumericVector test;
  NumericVector test2;
  for (int i = 0; i < mat.nrow(); i++){
    test = mat.row(i);
    if (test[0] == 1){
      test2 = test;
    }
  }
  return test2;
}

This function is supposed to output 1,1,1 , but instead it outputs 2,2,2 . However when I replace test2 = test with test2 = clone(test) then I get the correct output. So I was wondering why am I getting this behavior even though this is just assignment as Dirk suggested?

I gets easier when you look at all three as in the modified program below:

R> testvecs(c(2,2,2,2))
$test
[1] 2 2 2 2

$test2
[1] 1 1 1 1 1

$test3
[1] 1 1 1 1 1

R> 

where the (now complete) code is

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List testvecs(NumericVector test){
  NumericVector test2(test);
  NumericVector test3 = NumericVector::create(1,1,1,1,1);
  test2 = test3;
  return List::create(Named("test") = test,
                      Named("test2") = test2,
                      Named("test3") = test3);
}

/*** R
testvecs(c(2,2,2,2))
*/

So:

  • test is incoming and unaltered, no surprise on the outcome
  • test2 is created and then overwritten
  • test3 is freshly created, and comes out as expected
  • test2 is assigned to be the same as test3 , and it is.

I see no inconsistency here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM