Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Created October 24, 2013 16:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainfrancois/7140331 to your computer and use it in GitHub Desktop.
Save romainfrancois/7140331 to your computer and use it in GitHub Desktop.
using SETLENGTH to fool R about the size of a vector
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
x = <0x1038ff8a0>, dataptr = <0x1038ff8c8>
[[1]]
[1] 1
[[2]]
[1] 1.5
[[3]]
[1] 2
[[4]]
[1] 2.5
[[5]]
[1] 3
[[6]]
[1] 3.5
[[7]]
[1] 4
[[8]]
[1] 4.5
[[9]]
[1] 5
[[10]]
[1] 5.5
#define USE_RINTERNALS
#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>
SEXP means( SEXP x ){
int n = Rf_length(x) ;
SEXP res = PROTECT( Rf_allocVector( VECSXP, n ) ) ;
SEXP call = PROTECT( Rf_lang2( Rf_install( "mean"), x ) ) ;
for( int i=0; i<n; i++){
SETLENGTH(x, i+1 ) ;
SET_VECTOR_ELT( res, i, Rf_eval( call, R_GlobalEnv ) ) ;
Rprintf( "x = <%p>, dataptr = <%p> \n", x, DATAPTR(x) ) ;
}
UNPROTECT(2) ;
return res ;
}
system( "R CMD SHLIB vectors.c" )
dyn.load( "vectors.so")
x <- as.numeric(1:10)
means(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment