使用Rcpp模块将简单的C Student类暴露给R.
作者:互联网
我正在尝试使用包中的Rcpp在C到R中公开一个简单的Student类.这是我的设置……
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 */
Student.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 /
student.R
#' student
#'
#' A cool package
#'
#' Imports
#' @useDynLib student, .registration = TRUE
#' @importFrom Rcpp sourceCpp
"_PACKAGE"
Rcpp::loadModule(module = "Student", TRUE)
在调用devtools :: document()之后,我得到以下NAMESPACE文件
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),包编译并加载没有问题.如果我运行simulate_student()函数,我会得到预期的结果.但是,当我尝试用stud< - new(Student)创建一个新的Student对象时,我在.getClassesFromCache(Class)中得到错误:找不到对象'Student' 这个问题看起来与this SO post类似,但接受的答案似乎并没有解决我的问题.此外,我已经查看了Dirk提到的Annoy source code,但我没有看到该代码与我之间存在任何有用的差异,除了RCPP_EXPOSED_CLASS_NODECL(AnnoyEuclidean)片段,我尝试将其放在我的代码中但也没有帮助.
解决方法:
浏览这两个软件包,主要区别在于如何设置函数的导入和导出.
特别是,在NAMESPACE文件中,方法和Rcpp包都缺少为完全导入.此外,不是单独导出每个函数,而是使用全局导出模式.
RcppAnnoy
useDynLib(RcppAnnoy, .registration=TRUE)
import(methods, Rcpp)
exportPattern("^[[:alpha:]]+") # export all identifiers starting with letters
RcppStudent
roxygen2:
#' @useDynLib RcppStudent, .registration = TRUE
#' @import methods Rcpp
#' @exportPattern "^[[:alpha:]]+"
命名空间:
# Generated by roxygen2: do not edit by hand
exportPattern("^[[:alpha:]]+")
import(Rcpp)
import(methods)
useDynLib(RcppStudent, .registration = TRUE)
标签:c,r,rcpp 来源: https://codeday.me/bug/20190827/1745654.html