我使用Rcpp在R中创建一个利用C++代码的包。我已经阅读了所有的Rcpp小插曲,但我还没有找到解决以下问题的方法。
我尝试使用的一个C++类包含一个指针。我使用一个模块公开了这个类。当我试图在R中安装软件包时,我会得到以下错误。
error: expected unqualified-id before '*' token.field("*w", &ffm_model::*w)我做错了什么?
包含指针的类的代码
typedef float ffm_float;
typedef int ffm_int;
class ffm_model {
public:
ffm_int n; // number of features
ffm_int m; // number of fields
ffm_int k; // number of latent factors
ffm_float *w = nullptr;
bool normalization;
~ffm_model();
};相应RCPP模块的代码
RCPP_MODULE(ffmModelMod){
using namespace Rcpp;
//Expose class as ffm_model on the r side
class_<ffm_model>( "ffm_model")
.field("n", &ffm_model::n)
.field("m", &ffm_model::m)
.field("k", &ffm_model::k)
.field("*w", &ffm_model::*w)
.field("normalization", &ffm_model::normalization)
.method("~ffm_model",&ffm_model::~ffm_model)
;
}发布于 2018-12-17 11:11:15
我也遇到了类似的问题,正如Dirk提到的,这是由于无法自动映射的类型,例如float*。
以下解决方法适用于我:
get()和set()函数公开给上面的字段。下面是一个示例,其中隐藏(无问题的) value字段和(有问题的) child字段(指向同一类对象的指针):
类
#include <Rcpp.h>
using namespace Rcpp;
class node
{
public:
double value; // Voluntarily hidden from R
node* child; // Must be hidden from R
// Exposed functions
void setVal(double value);
double getVal();
node* createNode(double value); // return pointer to a node
node* createChild(double value); // set child
node* getChild();
};方法
void node::setVal(double value){
this->value = value;
}
double node::getVal(){
return this->value;
}
node* node::createNode(double value){
node* n = new node;
n->value = value;
return n;
}
node* node::createChild(double value){
this->child = createNode(value);
return child;
}
node* node::getChild(){
return this->child;
}RCPP模块
RCPP_MODULE(gbtree_module){
using namespace Rcpp;
class_<node>("node")
.constructor()
.method("setVal", &node::setVal)
.method("getVal", &node::getVal)
.method("createNode", &node::createNode)
.method("createChild", &node::createChild)
.method("getChild", &node::getChild)
;
}在R中的使用
n <- new(node)
n$setVal(2)
n$getVal()
n2 <- n$createNode(1) # unrelated node
n3 <- n$createChild(3) #child node
n$getChild() #pointer to child node
n3https://stackoverflow.com/questions/49519824
复制相似问题