<div>Hi all,</div><div><br></div><div>I have a class that stores data and various statistics about my data. I want to be able to work with it from R and from C++ functions, but I do not want to have the entire data structure created as an R object. I thought one might be able to return a pointer from the object to R, and pass that pointer from R to a C++ function that needs to interact with the object. This seems to work until garbage collection occurs, at which point I get a segfault.</div>
<div><br></div><div>I have included an example below illustrating my current approach. I altered the World example to return a pointer to the current object. I have a C++ function that makes changes to the object.</div>
<div><br></div><div>I saw this post <a href="http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2011-December/003214.html">http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2011-December/003214.html</a> but I wanted to use modules and I haven't been able to adapt that solution to my situation. </div>
<div><br></div><div>Any help/advice is much appreciated,</div><div>Chris</div><div><br></div><div>library(inline)</div><div>library(Rcpp)</div><div>fx <- cxxfunction(,"",includes=</div><div> '</div><div>
#include <Rcpp.h></div><div><br></div><div>class World {</div><div>public:</div><div> World() : msg("hello") {}</div><div> void set(std::string msg) { </div><div> this->msg = msg; </div><div> }</div>
<div> std::string greet() { </div><div> return msg; </div><div> }</div><div> SEXP ptr() {</div><div> return wrap(XPtr<World>(this, true));</div><div> }</div><div><br></div><div>private:</div><div> std::string msg;</div>
<div>};</div><div><br></div><div>int fn(SEXP ptr_) {</div><div> World *s = XPtr<World>(ptr_);</div><div> s->set("c++ function has been here");</div><div> return 1;</div><div>}</div><div><br></div><div>
RCPP_MODULE(example){</div><div>using namespace Rcpp ;</div><div>function("fn", &fn);</div><div>class_<World>( "World")</div><div> .constructor()</div><div> .method( "greet", &World::greet , </div>
<div> "get the message")</div><div> .method( "set", &World::set , </div><div> "set the message")</div><div> .method( "ptr", &World::ptr , </div><div> "get a pointer");</div>
<div>}</div><div>', plugin="Rcpp")</div><div><br></div><div>example <- Module("example",getDynLib(fx))</div><div><br></div><div>s <- new(example$World)</div><div><br></div><div># Interact with World object from R</div>
<div>s$greet()</div><div>s$set("hello from R")</div><div>s$greet()</div><div><br></div><div># Grab pointer to this World object</div><div>s$ptr() </div><div><br></div><div># Call a c++ function that uses World object</div>
<div>example$fn(s$ptr())</div><div>s$greet() # c++ function has altered s, as desired</div><div><br></div><div># Causes segfault</div><div>gc()</div><div><br></div>