【发布时间】:2018-12-06 20:52:14
【问题描述】:
我正在尝试使用包中的 Rcpp 将 C++ 中的一个简单 Student 类公开给 R。这是我的设置...
src/
Student.hpp// Student.hpp
#ifndef Student_hpp
#define Student_hpp
#include <string>
#include <vector>
class Student
{
public:
// Constructor
Student(std::string name, int age, bool male);
// Getters
std::string GetName();
int GetAge();
bool IsMale();
std::vector<int> GetFavoriteNumbers();
// Methods
bool LikesBlue();
private:
// Member variables
std::string name;
int age;
bool male;
std::vector<int> favoriteNumbers;
};
#endif /* Student_hpp */
学生.cpp
// Student.cpp
#include "Student.hpp"
// Constructor
Student::Student(std::string name, int age, bool male) {
this->name = name;
this->age = age;
this->male = male;
this->favoriteNumbers = {2, 3, 5, 7, 11};
}
// Getters
bool Student::IsMale() { return male; }
int Student::GetAge() { return age; }
std::string Student::GetName() { return name; }
std::vector<int> Student::GetFavoriteNumbers() { return favoriteNumbers; }
// Methods
bool Student::LikesBlue() {
return (male || age >= 10);
}
glue.cpp
// glue.cpp
// To use c++11, first run: Sys.setenv("PKG_CXXFLAGS"="-std=c++11") ...or use a Makevars file
#include <Rcpp.h>
#include "Student.hpp"
using namespace Rcpp;
//' Simulate a student
//'
//' @export
// [[Rcpp::export]]
std::vector<int> simulate_student() {
Student s = Student("bob", 10, true);
return s.GetFavoriteNumbers();
}
// Expose (some of) the Student class
RCPP_MODULE(Student){
class_<Student>("Student")
.constructor<std::string,int,bool>()
.method("LikesBlue", &Student::LikesBlue)
;
}
R/
学生.R#' student
#'
#' A cool package
#'
#' Imports
#' @useDynLib student, .registration = TRUE
#' @importFrom Rcpp sourceCpp
"_PACKAGE"
Rcpp::loadModule(module = "Student", TRUE)
调用devtools::document()后,得到如下的NAMESPACE文件
# Generated by roxygen2: do not edit by hand
export(simulate_student)
importFrom(Rcpp,sourceCpp)
useDynLib(student, .registration = TRUE)
现在,在从 RStudio(即R CMD INSTALL --preclean --no-multiarch --with-keep.source student)执行 clean and rebuild 之后,包编译和加载没有问题。如果我运行 simulate_student() 函数,我会得到预期的结果。但是,当我尝试使用 stud <- new(Student) 创建一个新的 Student 对象时,我得到 Error in .getClassesFromCache(Class) : object 'Student' not found
这个问题似乎类似于this SO post,但接受的答案似乎并没有解决我的问题。此外,我查看了 Dirk 提到的Annoy source code,但我没有看到该代码与我的代码之间有任何有用的区别,除了我尝试在我的代码中放置但也这样做的RCPP_EXPOSED_CLASS_NODECL(AnnoyEuclidean) sn-ps没用。
【问题讨论】:
-
以this guide 为参考,我没有看到任何类型的
unif_module <- Module( "unif_module", getDynLib(fx_unif ) )语句来定义R 领域中的模块。