R6 类与 Rcpp 模块桥接:在 R 中直接调用 C++ 方法
展示如何用 Rcpp 模块将 C++ 类暴露为 R6 引用类,实现方法级调用而无需重复 .Call。适合需要维护状态的图形、缓存或模拟引擎。 · 难度:入门 · +10XP
R6 外壳,C++ 内核
Rcpp 模块允许用 C++ 定义类并直接在 R 中 new,但接口不够友好。用 R6 做封装层,可以添加输入验证、S3 方法和文档。以下 C++ 类 Counter 被 export 后由 R6 代理:
// C++ 部分
class Counter {
public:
int val = 0;
void increment() { val++; }
int get() const { return val; }
};
RCPP_MODULE(counter_mod) {
class_("CounterCpp")
.constructor()
.method("increment", &Counter::increment)
.method("get", &Counter::get);
} # R 部分
CounterR6 <- R6::R6Class("CounterR6",
private = list(cpp = NULL),
public = list(
initialize = function() private$cpp <- new(CounterCpp),
inc = function() private$cpp$increment(),
value = function() private$cpp$get()
)
)