在 Rcpp 中公开类 - 工厂而不是构造函数 [英] expose class in Rcpp - factory instead of constructor
问题描述
有一个类我必须移植到 R.我将它作为 Rcpp 模块公开.但是,我还需要在 R 之外使用该类.我的意思是我想用谷歌测试来测试这门课.为了编译测试,该类不得使用 Rcpp 中的任何内容.
There is a class I have to port to R. I have exposed it as a Rcpp module. However, I need to use that class outside of R also. I mean I want to test the class with google tests. In order to compile the tests the class must not use anything from Rcpp.
不幸的是,创建类实例的函数必须具有相当灵活的参数列表.我想使用命名参数,因为您可以选择指定许多参数.出于这个原因,我不能声明在 R 中有任何用处的构造函数.如果我可以定义一个作为工厂方法执行的函数,那就没问题了.我做到了.
Unfortunately, the function creating an instance of the class has to have quite flexible argument list. I would like to use named arguments since there will be many arguments you may choose to specify. For that reasons I cannot declare constructor that would be of any use within R. It would be ok, if I could define a function that would perform as a factory method. I did.
RcppExport SEXP CEC__new(SEXP args);
RCPP_MODULE(cec) {
using namespace Rcpp;
class_<CEC>("cec")
.method("test", &CEC::test)
.method("loop", &CEC::loop)
.method("singleLoop", &CEC::singleLoop)
.method("entropy", &CEC::entropy)
;
}
setClass("cec", representation(pointer = "externalptr"))
setMethod("initialize", "cec", function(.Object, ...) {
.Object@pointer <- .Call("CEC__new", ...)
.Object
})
问题是我无法调用我创建的实例的任何方法.看起来我必须为 R 中的类定义$".我不想那样做.我想利用 Rcpp 模块提供的漂亮、紧凑的形式.你能建议我如何解决这个问题吗?
The problem is that I cannot call any methods of the instance I create. It looks like I have to define '$' for the class within R. I don't want do that. I would like to take advantage of the pretty, compact form Rcpp module offers. Can you suggest me how to solve this issue?
推荐答案
您可以使用 .factory
将一个自由函数注册为您的类的构造函数,但在这种情况下,该函数应返回一个指向 CEC
的指针.像这样:
You can use .factory
for registering a free function as a constructor to your class, but in that case the function should return a pointer to a CEC
. Something like this:
CEC* CEC__new(SEXP args);
RCPP_MODULE(cec) {
using namespace Rcpp;
class_<CEC>("cec")
.factory( CEC__new )
.method("test", &CEC::test)
.method("loop", &CEC::loop)
.method("singleLoop", &CEC::singleLoop)
.method("entropy", &CEC::entropy)
;
}
或者:
.factory<SEXP>( CEC__new )
这篇关于在 Rcpp 中公开类 - 工厂而不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!