0

我正在使用 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)
    ;
}
4

1 回答 1

0

我遇到了类似的问题,正如 Dirk 所提到的,这是由于无法自动映射的类型,例如float*.

以下解决方法对我有用:

  1. 不要将具有问题类型的字段暴露给 R。
  2. 相反,向上面的字段公开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
n3
于 2018-12-17T11:11:15.617 回答