[Rcpp-devel] pointer to c++ object with modules

Chris DuBois chris.dubois at gmail.com
Mon Feb 6 19:40:29 CET 2012

Hi all,

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

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.

I saw this post
but I wanted to use modules and I haven't been able to adapt that
to my situation.

Any help/advice is much appreciated,

fx <- cxxfunction(,"",includes=
#include <Rcpp.h>

class World {
  World() : msg("hello") {}
  void set(std::string msg) {
    this->msg = msg;
  std::string greet() {
    return msg;
  SEXP ptr() {
    return wrap(XPtr<World>(this, true));

  std::string msg;

int fn(SEXP ptr_) {
  World *s = XPtr<World>(ptr_);
  s->set("c++ function has been here");
  return 1;

using namespace Rcpp ;
function("fn", &fn);
class_<World>( "World")
  .method( "greet", &World::greet ,
  "get the message")
  .method( "set", &World::set ,
  "set the message")
  .method( "ptr", &World::ptr ,
  "get a pointer");
', plugin="Rcpp")

example <- Module("example",getDynLib(fx))

s <- new(example$World)

# Interact with World object from R
s$set("hello from R")

# Grab pointer to this World object

# Call a c++ function that uses World object
s$greet()  # c++ function has altered s, as desired

# Causes segfault
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20120206/41d60744/attachment.html>

More information about the Rcpp-devel mailing list