Rcpp: Calling function with object as argument

Viewed 262

I have a function in Rcpp, which creates a very long map-structure within a class. I've given a simple example of it below:

#include <Rcpp.h>
using namespace Rcpp;

class A{
private:
  std::map<int, int> m_map;
public:
  void fill_map(const size_t limit){
    for(size_t i=0; i<limit; ++i){
      m_map[i] = i;
    }
  }
  size_t size_map(){return m_map.size();}
};

// [[Rcpp::export]]
void func1(const size_t limit) {
  A a;
  a.fill_map(limit);
}

/* NOT WORKING */
// [[Rcpp::export]]
void func2(A a)
{
  std::cout << a.size_map() << "\n";
}
/* NOT WORKING */

Say I call func1(1e7), which fills up the map in the a-object. I need to pass this A-object to other functions as shown above with func2.

However, my example with func2 doesn't work. Within the Rcpp-framework, what is the correct and most efficient approach to call func2 with an object defined in a previous function?

1 Answers

C++ code

#include <Rcpp.h>
using namespace Rcpp;

class A
{
  private:
    std::map<int, int> m_map;

  public:
    void fill_map(const size_t limit)
    {
      for(size_t i=0; i<limit; ++i)
      {
        m_map[i] = i;
      }
    }

    size_t size_map(){return m_map.size();}
};

// [[Rcpp::export]]
XPtr<A> func1(const size_t limit)
{
  XPtr<A> ptr(new A(), true);
  ptr->fill_map(limit);
  return(ptr);
}

// [[Rcpp::export]]
void func2(XPtr<A> ptr)
{
  Rcout << ptr->size_map() << std::endl;
}

R code

a = func1(10)
func2(a)

a being an External pointer.

Related