【问题标题】:Can Rcpp expose a C++ class method taking a reference to the same class?Rcpp 可以公开一个引用同一类的 C++ 类方法吗?
【发布时间】:2015-02-13 18:16:49
【问题描述】:

当一个 C++ 类有一个成员获取该类的实例时,是否可以使用 Rcpp 向 R 公开该类?

例子:

#include <Rcpp.h>

class Test {
public:
    Test(int x): x_(x) {}
    int getValue() { return x_; }
    void addValue(int y) { x_ += y; }
    void merge(const Test& rhs) { x_ += rhs.x_; }
private:
    int x_;
};

using namespace Rcpp;

RCPP_MODULE(mod_test) {

    class_<Test>("Test")

    .constructor<int>("sets initial value")

    .method("getValue", &Test::getValue, "Returns the value")
    .method("addValue", &Test::addValue, "Adds a value")
    .method("merge", &Test::merge, "Merges another Test into this object")
    ;
}

不幸的是,这会导致以下错误:

错误:'Test' 的初始化没有匹配的构造函数

在阅读和搜索答案后,我想出了单独包含RcppCommon.h然后插入如下块的习语:

namespace Rcpp {
    template <> Test as( SEXP x ) ;
}

很遗憾,这会导致以下错误:

dyn.load("/.../sourceCpp_86871.so") 中的错误:无法加载 共享对象'/.../sourceCpp_86871.so':
dlopen(/.../sourceCpp_86871.so, 6):找不到符号: __ZN4Rcpp2asI4TestEET_P7SEXPREC 引用自:/.../sourceCpp_86871.so 预期于:平面命名空间 /.../sourceCpp_86871.so

可以这样做吗?

是否有我需要创建的“as”专业化的实现?在某处有如何编写它的示例吗?

或者,是否有一个示例说明如何检查 SEXP 并将其转换回它“包装”的 C++ 对象?

【问题讨论】:

标签: c++ r rcpp


【解决方案1】:

正确的as 转换似乎是通过插入RCPP_EXPOSED_CLASS 生成的。

完整的工作示例变为:

#include <Rcpp.h>

class Test {
public:
    Test(int x): x_(x) {}
    int getValue() { return x_; }
    void addValue(int y) { x_ += y; }
    void merge(const Test& rhs) { x_ += rhs.x_; }
private:
    int x_;
};

using namespace Rcpp;

RCPP_EXPOSED_CLASS(Test)
RCPP_MODULE(mod_test) {

    class_<Test>("Test")

    .constructor<int>("sets initial value")

    .method("getValue", &Test::getValue, "Returns the value")
    .method("addValue", &Test::addValue, "Adds a value")
    .method("merge", &Test::merge, "Merges another Test into this object")
    ;
}

现在可以正常工作了:

> Rcpp::sourceCpp('test.cpp')
> a = Test$new(2)
> b = Test$new(3)
> a$getValue()
[1] 2
> a$merge(b)
> a$getValue()
[1] 5

【讨论】:

  • 非常好的例子。我没有尝试过/不需要这个,但是有这个很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 2011-02-15
相关资源
最近更新 更多