使用Rcpp :: Nullable与RcppArmadillo类型时出错

时间:2017-05-28 19:10:20

标签: rcpp

我在R包中使用RcppArmadillo,我想在参数列表中使用Rcpp :: Nullable。

NumericVector d_snb(NumericVector& x,
                Nullable<arma::mat> size_param = R_NilValue,
                const int& infinite = 100000, const bool& log_v = false)

这会产生如下错误:

Error: package or namespace load failed for ‘packagex’ in dyn.load(file, DLLpath = DLLpath, ...): unable to load shared object '/usr/local/lib/R/3.4/site-library/packagex/libs/packagex.so': dlopen(/usr/local/lib/R/3.4/site-library/packagex/libs/packagex.so, 6): 
Symbol not found: __Z5d_snbRN4Rcpp6VectorILi14ENS_15PreserveStorageEEENS_8NullableIS2_EES5_S5_RKiRKb
Referenced from: /usr/local/lib/R/3.4/site-library/packagex/libs/packagex.so
Expected in: flat namespace in /usr/local/lib/R/3.4/site-library/packagex/libs/packagex.so
Error: loading failed
Execution halted

现在唯一可行的解​​决方案似乎是将参数作为NumericVector获取,然后获取内容然后将其转换为Armadillo类型。

NumericVector d_snb(NumericVector& x,
                Nullable<NumericVector> size_param = R_NilValue ...)
{
...

  if(size_param.isNotNull()) {
    arma::mat test(NumericVector(size_param));
    param_check++;
  }
...
}

这会发出警告:

d_snb.cpp:36:21: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
  arma::mat test(NumericVector(size_param));
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~
d_snb.cpp:36:22: note: add a pair of parentheses to declare a variable
  arma::mat test(NumericVector(size_param));
                 ^
                 (                        )
1 warning generated.

最好的方法是什么?

1 个答案:

答案 0 :(得分:3)

是的,Rcpp::Nullable<>仅适用于基于SEXP的Rcpp类型。

所以你必须完成你找到的两步程序。但我认为你可以做一个更简单的事:arma::mat test = Rcpp::as<arma::mat>(size_param);

这是一个完整的例子,它编译(但没有&#39;没有&#39;):

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void d_snb(Rcpp::NumericVector& x,
           Rcpp::Nullable<Rcpp::NumericVector> size_param = R_NilValue) {

  if (size_param.isNotNull()) {
    arma::vec test = Rcpp::as<arma::vec>(size_param);
    test.print("vector");
  }
  Rcpp::Rcout << x << std::endl;

}

快速演示:

R> sourceCpp("/tmp/so44102346.cpp")
R> d_snb(c(1,2,3))
1 2 3
R> d_snb(c(1,2,3), c(4,5,6))
vector
   4.0000
   5.0000
   6.0000
1 2 3
R>