[Rcpp-devel] Persistent C++ objects in R ( tree data structure )

Ariful Azad azadcse at gmail.com
Thu Apr 4 21:13:40 CEST 2013


Hello Everybody,

I am trying to create tree data structure using C++ and Rcpp and use it
from R.
I want to incrementally build the tree by merging a tree with other tress.
So, I created a class for the tree and a class for the nodes in the tree.
The tree class has two constructors, the first one simply creates a tree
with a single leaf. The second constructor takes two external pointers
pointing to two trees and creates a new tree be joining the two trees with
a new node. In the R side I create a tree (tree1) and repeatedly add
another tree (tree2) in the first tree. Here is the C++ and R code.


#include <Rcpp.h>
class treeNode
{
public:
  treeNode* left;
    treeNode* right;
};

class tree
{
private:
   treeNode* root;
public:
    tree();
    tree(SEXP, SEXP);
    SEXP getPointer();
    void addTree(SEXP ptr2);
};


tree::tree()
{
  root = new treeNode;
  root->left = NULL;
  root->right = NULL;
}

// merge two tree and create a new tree
tree::tree(SEXP ptr1, SEXP ptr2)
{
  Rcpp::XPtr<tree> tree1(ptr1);
  Rcpp::XPtr<tree> tree2(ptr2);

  root = new treeNode;
  root->left = tree1->root;
  root->right = tree2->root;
}

SEXP tree::getPointer()
{
  Rcpp::XPtr<tree> ptr(this, true);
  return ptr;
}

RCPP_MODULE(yada){
  using namespace Rcpp ;
    class_<tree>("tree")
            .constructor()
            .constructor<SEXP, SEXP>("create a new tree by merging two
existing trees")
            .method("getPointer", &tree::getPointer, "getPointer")
            ;
}


I created a package called test and then call the functions from  R side
The R code looks like the following:

require(test)

t1 = new(tree)
t2 = new(tree)
t1 = new(tree, t1$getPointer(), t2$getPointer())
gc()

t2 = new(tree)
t1 = new(tree, t1$getPointer(), t2$getPointer())
gc()


After second garbage collector call I am getting segmentation fault . Can
you please explain the right way to program this scenario? In particular,
when a C++ object is still used by another object through pointer how can I
prevent R garbage collector removing the object ?


Thanks

Ariful Azad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130404/77bf1214/attachment.html>


More information about the Rcpp-devel mailing list