[Rd] How to preserve data across function calls in a library package

From: Saptarshi Guha <sapsi_at_pobox.com>
Date: Tue, 10 Jul 2007 11:41:13 -0400


        I am writing an R package with two functions in C++. So far everything works.

        Now, i would like to write a third function which would use a pointer (it is a pointer to a class object) created by first function.

        I tried placing this pointer outside of the function definitions (i.e to make it global) but when called in the 3rd function i get
> *** caught bus error ***
address 0x0, cause 'invalid alignment'"

        I tried Callocing it in the 1st function but to no avail. Here is a quick summary. When foo is called (through do_foo, **after** having called do_kNN_e) i get the aforementioned error.

        Can anyone provide some pointers (no pun intended) on this?


ANN* book;
int* foot;

void foo(void){

   Rprintf("many times\n");


kNN_e(SEXP data, SEXP Nrow, SEXP Ncol,SEXP K,SEXP Eps) {

   int nrow=asInteger(Nrow);
   int ncol=asInteger(Ncol);
   int k=asInteger(K);
   double eps=asReal(Eps);

   SEXP ans,distance;
   SEXP retlist;
   PROTECT(ans=allocMatrix(INTSXP,nrow,k)); //The 2nd argument gives the number of rows, and the last the number of cols see http://cran.r- project.org/doc/manuals/R-exts.html

   PROTECT(distance=allocMatrix(REALSXP,nrow,k));    ANNpointArray datapoints;
   ANNpoint qpoint;
   ANNkd_tree* kdTree;



extern "C" {

   void do_foo(void){

do_kNN_e(SEXP data, SEXP Nrow, SEXP Ncol,SEXP k,SEXP eps) {

   return kNN_e(data,Nrow, Ncol,



        [[alternative HTML version deleted]]

R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Tue 10 Jul 2007 - 17:06:30 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 10 Jul 2007 - 18:36:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.