我试图通过构建一个包来通过Rcpp公开我的C ++类。似乎模块不允许在RStudio自动生成的模板中。例如,如果我们比较Rcpp.package.skeleton(myPackage, module=TRUE)
和RStudio生成的NAMESPACE文件,importFrom(Rcpp, loadModule)
不在RStudio NAMESPACE文件中。我错过了什么?如何启用RStudio生成模块允许的包模板?
这是一个显示我的C ++代码的最小例子,以防有人想在RStudio中试用它
class Student{
private:
double age;
double GPA;
public:
Student(double age_, double GPA_):age(age_),GPA(GPA_){}
double sum(double x, double myGPA){
GPA = myGPA;
return GPA + x;
}
double times(double x, double myage){
age = myage;
return age*GPA*x;
}
};
RCPP_MODULE(my_module){
class_<Student>("Student")
.constructor<double, double>()
.method("sum", &Student::sum)
.method("times",&Student::times);
}
答案 0 :(得分:3)
非常非常简短:不,或者“有点”,不完全“。
进一步扩展:自动包存根创建一个可用的基本Rcpp包。但是,例如,不是RcppArmadillo包(之前有人咬过)。
我们在包in this directory中为Rcpp模块提供了一个完整的示例(由单元测试使用),因此如果您需要手动执行几个步骤走那条路。
你也可以尝试使用另一个正式选项Rcpp.package.skeleton()
的帮助函数module=TRUE
。
总而言之,您无法合理地期望RStudio GUI支持所有可用的排列。
答案 1 :(得分:3)
简单地说,RStudio在为此版本(1.0)生成Rcpp项目类型方面受到限制。根据{{3}},自定义包模板即将投放!
要解决此限制,请尝试以下操作:
Rcpp.package.skeleton("myPackage", module=TRUE)
New Project
- &gt; From Existing Directory
或使用devtools::use_rstudio()
生成.Rproj
。根据评论,真正发生的事情有两个:
首先,模块定义需要更新为:
#include <Rcpp.h>
class Student{
private:
double age;
double GPA;
public:
Student(double age_, double GPA_):age(age_),GPA(GPA_){}
double sum(double x, double myGPA){
GPA = myGPA;
return GPA + x;
}
double times(double x, double myage){
age = myage;
return age*GPA*x;
}
};
RCPP_MODULE(my_module){
using namespace Rcpp ; // Added (if not done globally)
class_<Student>("Student")
.constructor<double, double>()
.method("sum", &Student::sum, "Sum") // Add some documentation (optional)
.method("times",&Student::times, "Times");
}
接下来,在一些 R 代码文件中添加:
loadModule("my_module", TRUE)
构建和重新加载
然后,你有:
s <- new( Student, 1, 2 )
s$sum(2,4)
# [1] 6
s$times(5,6)
# [1] 120