RCPP-公开一个包含指针的C 函数



我正在使用rcpp在R中创建一个利用C 代码的软件包。我已经阅读了所有RCPP小插曲,但是我找不到解决以下问题的解决方案。

我要使用的C++类之一包含指针。我正在使用模块公开课程。当我尝试在R中安装软件包时,我会收到以下错误。

error: expected unqualified-id before '*' token.field("*w", &ffm_model::*w)

我在做什么错?

code for类包含指针

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)
    ;
}

我也有类似的问题,正如德克所述,这是由于无法自动映射的类型,例如float*

以下解决方法对我有用:

  1. 不要将有问题类型的领域暴露于r。
  2. 相反,将get()set()函数公开到上面的字段。

这是一个示例,其中(毫无疑问的(value字段和(有问题的(child字段(指向同一类的对象的指针(都隐藏了:

class

#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
n3

最新更新