Tho*_*orf 14 c++ module r 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)
不过,我不知道如何将对象作为参数返回到方法/函数中.以下不起作用:
template <> A* as( SEXP obj){
Rcpp::List l(obj);
Rcpp::XPtr<A> xp( (SEXP) l[".pointer"] );
return (A*) xp;
}
Run Code Online (Sandbox Code Playgroud)
那么如何从参数列表中作为SEXP提供的S4对象获取指向C++对象的外部指针?
Rom*_*ois 12
此功能已添加到Rcpp 0.10.0中
您的代码无法编译的原因还有其他原因.以下代码适用于我:
class A {
public:
A(int x_) : x(x_){}
int x;
};
class B {
public:
A get_an_a(){
A an_a(3);
return an_a;
}
};
RCPP_EXPOSED_CLASS(A)
RCPP_EXPOSED_CLASS(B)
RCPP_MODULE(stackmod){
using namespace Rcpp ;
class_<A>("A")
.constructor<int>()
.field("x",&A::x)
;
class_<B>("B")
.constructor()
.method("get_an_A",&B::get_an_a)
;
}
Run Code Online (Sandbox Code Playgroud)
付出的代价是RCPP_EXPOSED_CLASS为所有类调用宏:
有了这个,我得到:
> b <- new( B )
> b$get_an_A( )
C++ object <0x10330a9d0> of class 'A' <0x1006f46e0>
> b$get_an_A( )$x
[1] 3
Run Code Online (Sandbox Code Playgroud)
如果你为它编写一个包装器,这是可能的。这些不会像天上掉下来的甘露一样,你需要通过提供它来帮助编译器,然后它就会被选择。
RcppBDT 的简单示例:
template <> SEXP wrap(const boost::gregorian::date &d) {
// convert to y/m/d struct
boost::gregorian::date::ymd_type ymd = d.year_month_day();
return Rcpp::wrap(Rcpp::Date( ymd.year, ymd.month, ymd.day ));
}
Run Code Online (Sandbox Code Playgroud)
这里,Boost 中的类被转换为 Rcpp 类(Date),然后返回(即使在那里,我们也需要显式包装)。对于更复杂的类,您需要更复杂的转换器。
编辑:当然,您需要记住,任何可从 R 调用的内容仍然需要SEXP foo(SEXP a, SEXP b, ...)符合.Call().
| 归档时间: |
|
| 查看次数: |
2288 次 |
| 最近记录: |