Rcpp - 在包结构之外编译

Rcpp - Compiling outside the structure of a package

我有一个关于在包结构之外使用 Rcpp 使用 C++ 代码的问题。

为了澄清我的疑问,请考虑下面的 C++ 代码 (test.cpp):

// [[Rcpp::depends(RcppGSL)]]

#include <Rcpp.h>
#include <numeric>
#include <gsl/gsl_sf_bessel.h>
#include <RcppGSL.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
  return x * 2;
}

// [[Rcpp::export]]
double my_bessel(double x){
  return gsl_sf_bessel_J0 (x);
}

// [[Rcpp::export]]
int tamanho(NumericVector x){
  int n = x.size();

  return n;
}

// [[Rcpp::export]]
double soma2(NumericVector x){
  double resultado = std::accumulate(x.begin(), x.end(), .0);
  return resultado; 
}

// [[Rcpp::export]]
Rcpp::NumericVector colNorm(const RcppGSL::Matrix & G) {
  int k = G.ncol();
  Rcpp::NumericVector n(k);           // to store results
  for (int j = 0; j < k; j++) {
    RcppGSL::VectorView colview = gsl_matrix_const_column (G, j);
    n[j] = gsl_blas_dnrm2(colview);
  }
  return n;                           // return vector
}

以上代码在包结构内时有效。正如我们所知,使用 Rcpp::compileAttributes() 创建文件 RcppExports.cpp。这样我就可以访问 R. 环境中的函数了。

我的兴趣是在包的框架之外使用使用 Rcpp 实现的 C++ 函数。为此,我使用 g ++ 编译器编译了 C++ 代码,如下所示:

g++ -I"/usr/include/R/" -DNDEBUG -I"/home/pedro/R/x86_64-pc-linux-gnu-library/3.5/Rcpp/include" -I"/home/pedro/Dropbox/UFPB/Redes Neurais e Análise de Agrupamento/Rcpp" -I /home/pedro/R/x86_64-pc-linux-gnu-library/3.5/RcppGSL/include -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong -fno-plt  -c test.cpp -o test.o -lgsl -lgslcblas -lm
g++ -shared -L/usr/lib64/R/lib -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -o produto.so produto.o -L/usr/lib64/R/lib -lR -lgsl -lgslcblas -lm

编译成功,没有发出警告信息。这样就生成了test.otest.so文件。已经在 R 中,使用 .Call 界面,我做了:

dyn.load("test.so")

my_function <- function(x){
    .Call("soma2",x)
}

尝试使用 my_function () 函数时,出现错误,指出 soma2 不在加载 table 中。有没有办法在包的框架之外创建 RcppExports.cpp 文件?我想正确的做法是编译代码 RcppExports.cpp 而不是 test.cpp.

提前致谢。

如果您在包外工作,您可以简单地使用 Rcpp::sourceCpp(<file>)。这将为您编译、链接和生成 R 包装器。有了你的文件,我得到:

> Rcpp::sourceCpp("test.cpp")
> soma2(1:5)
[1] 15