Skip to content
Prev 2660 / 10988 Next

[Rcpp-devel] Pointer troubles

Hi Dirk and list,

Indeed it might have been a bit too complicated.
I think I have another example, which explains my troubles without
requiring OpenCL.
In this case, I want to return a pointer to an integer value to R and
the double the integer value in another function.
(I know this is stupid to do, but it is a toy example)

// Stuff to expose the int to R
static void intObjFinalizer(SEXP ref){
       if(TYPEOF(ref) == EXTPTRSXP){
               int *o = static_cast<int*> (R_ExternalPtrAddr(ref));
               if (o) delete o;
       }
}

SEXP int2EXP(int *o){
       SEXP xp = R_MakeExternalPtr(o, R_NilValue, R_NilValue);
       R_RegisterCFinalizerEx(xp, intObjFinalizer, TRUE);
       return xp;
}

int *SEXP2int(SEXP o){
       if(TYPEOF(o) != EXTPTRSXP)
               Rf_error("invalid object");
       return (int*) R_ExternalPtrAddr(o);
}

SEXP getIntPointer(){
    int test = 6;
    SEXP retVal = int2EXP(&test);
    std::cout << test << "\n";
    int test2 = *SEXP2int(retVal);
    std::cout << test2 << "\n";
    return retVal;
}

SEXP doubleIntPointer(SEXP test){
    int test2 = *SEXP2int(test);
    std::cout << test2;
    return Rcpp::wrap(test2*2);
}

By the way, I use a module to expose these functions:

RCPP_MODULE(ropencl){
	using namespace Rcpp ;
    function( "getIntPointer"  , &getIntPointer , "getIntPointer" ) ;
    function( "doubleIntPointer"  , &doubleIntPointer , "doubleIntPointer" ) ;
}

When I now execute getIntPointer() from R, it seems to work fine, both
the initial integer and the value that I get back from
*SEXP2int(retVal); are 6. (Although when I exit R after only this call
I get the following: *** glibc detected *** /usr/lib64/R/bin/exec/R:
free(): invalid pointer: 0x00007fffd1a587cc ***)

However, when I now use doubleIntPointer(getIntPointer()) in R, I get
some wrong result (a different value each time I restart R).

Does this make it a bit more clear what I want to do, or the problems
that I am facing?

Kind regards,

Willem
On Tue, Aug 2, 2011 at 15:24, Dirk Eddelbuettel <edd at debian.org> wrote: