相关疑难解决方法(0)

从Rcpp中的包装方法返回自定义对象

我对Rcpp模块有以下问题:让我们假设我在Rcpp模块中有两个类

class A {
  public:
    int x;
};

class B
  public:
    A get_an_a(){
      A an_a();
      an_a.x=3;
      return an_a;
    }
};

RCPP_MODULE(mod){
  using namespace Rcpp ;
  class_<A>("A")
   .constructor()
   .property("x",&A::get_x)
  ;
  class_<B>("B)
   .constructor()
   .method("get_an_A",&get_an_a)
  ;
}
Run Code Online (Sandbox Code Playgroud)

.

现在编译失败了,因为它不知道如何处理A的返回类型.

我想我可以用Rcpp :: Xptr做一些事情然而,然后我无法将它连接到Rcpp为类A生成的S4结构.我实际上从R中的方法获得了一个外部指针对象.

是否有可能从第二类的方法中获取正确包装的对象?

谢谢,托马斯

[编辑]

根据Dirk的回答,我构造了一个可以创建包装的S4对象的包装器:

template <> SEXP wrap(const A &obj) { // insprired from "make_new_object" from Rcpp/Module.h
  Rcpp::XPtr<A> xp( new A(obj), true ) ; // copy and mark as finalizable
  Function maker=Environment::Rcpp_namespace()[ "cpp_object_maker"];
  return maker ( typeid(A).name() , xp );
} …
Run Code Online (Sandbox Code Playgroud)

c++ module r rcpp

14
推荐指数
2
解决办法
2288
查看次数

将c ++对象作为指针传递给Rcpp中的另一个函数重用

假设我在C++中有以下两个函数:

// [[Rcpp::export]]
SEXP foo() {

  int a = 1;

  Rcpp::XPtr<int> ptr(&a, true);

  return ptr;
}

// [[Rcpp::export]]
int bar(SEXP a){

  Rcpp::XPtr<int> x(a);
  int b = *x;

  return b;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够在R中调用类似下面的内容.当然,在这个例子中我可以返回一个int到R in foo,但在我的原始代码中,a是一个有点复杂的数据结构,我不想只返回指针为此,它可以被另一个被调用的C++函数重用bar

a <- foo()
bar(a)
Run Code Online (Sandbox Code Playgroud)

在这个例子中我期望bar(a)返回1而不是0.我该如何解决这个问题?

c++ r rcpp

8
推荐指数
1
解决办法
381
查看次数

标签 统计

c++ ×2

r ×2

rcpp ×2

module ×1