Rcpp - 在包的结构外编译

时间:2018-05-26 21:39:49

标签: c++ r rcpp

我有一个关于在包结构之外使用 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不在加载表中。有没有办法在包的框架之外创建RcppExports.cpp文件?我想正确的一个是编译代码RcppExports.cpp而不是test.cpp

提前致谢。

1 个答案:

答案 0 :(得分:5)

如果您在包外工作,只需使用Rcpp::sourceCpp(<file>)即可。这将负责编译,链接和为您提供R包装。有了你的文件,我得到了:

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