【问题标题】:cannot convert 'SEXP' to 'Rcpp::traits::input_parameter<double>无法将 'SEXP' 转换为 'Rcpp::traits::input_parameter<double>
【发布时间】:2016-09-18 09:39:59
【问题描述】:

当我想运行以下 cpp 代码时

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]

void print_mat(double *Mat, int nbLig, int nbCol) {

 int i, j;

 for (i = 0; i < nbLig; i++) {

  for (j = 0; j < nbCol; j++)

    printf("%f ", *(Mat + (nbCol * i) + j));

    putchar('\n');
  }
}

通过 Rcpp 和 sourceCpp 命令

我明白了

无法将参数 '1' 的 'Rcpp::traits::input_parameter::type {aka Rcpp::InputParameter}' 转换为 'double*' 到 'void print_mat(double*, int, int)' print_mat(*Mat, nbLig, nbCol)

如何消除此错误

【问题讨论】:

  • 第二个 for 循环末尾缺少的左大括号是否是错字,您的代码中是否也缺少它?

标签: c++ shared-libraries rcpp


【解决方案1】:

简单地说:

  • 您的界面全错了,这不是我们从 R 传递矩阵的方式;查看大量发布的示例和文档
  • 这样,矩阵访问是错误的
  • 使用Rprintf() 打印每个编写 R 扩展

因此需要修复版本:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void print_mat(NumericMatrix Mat) {
  int nbLig = Mat.nrow(), nbCol = Mat.ncol();
  int i, j;
  for (i = 0; i < nbLig; i++) {
    for (j = 0; j < nbCol; j++)
      Rprintf("%f ", Mat(i,j));
    Rprintf("\n");
  }
}

/*** R
print_mat(matrix(1:9,3))
*/

我还包括了一个示例用法。将其拉入 R 产生

R> sourceCpp("/tmp/foomat.cpp")

R> print_mat(matrix(1:9,3))
1.000000 4.000000 7.000000 
2.000000 5.000000 8.000000 
3.000000 6.000000 9.000000 
R> 

不用说,你也可以通过一个命令得到这个:

// [[Rcpp::export]]
void print_mat2(NumericMatrix Mat) {
  print(Mat);
}

它为您提供 R 中的行和列标题:

R> print_mat2(matrix(1:9,3))
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
R> 

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 2018-08-09
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多