gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:38:12 26 4
gpt4 key购买 nike

我对 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)
;
}

.

现在编译失败,因为它不知道如何处理 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 );
}

不过,我不知道如何将对象作为参数返回给方法/函数。以下方法不起作用:

template <> A* as( SEXP obj){
Rcpp::List l(obj);
Rcpp::XPtr<A> xp( (SEXP) l[".pointer"] );
return (A*) xp;
}

那么如何从参数列表中作为 SEXP 提​​供的 S4 对象中获取指向 C++ 对象的外部指针?

最佳答案

此功能已在 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)
;
}

付出的代价是为所有类调用宏RCPP_EXPOSED_CLASS:

  • 您的一个模块正在暴露
  • 您想作为公开方法的结果或作为参数使用

有了这个,我得到:

> b <- new( B )
> b$get_an_A( )
C++ object <0x10330a9d0> of class 'A' <0x1006f46e0>
> b$get_an_A( )$x
[1] 3

关于c++ - 从 Rcpp 中的包装方法返回自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12405655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com