Rcpp - 在包结构之外编译

Rcpp - Compiling outside the structure of a package

本文关键字:编译 结构 包结构 Rcpp      更新时间:2023-10-16

我有一个关于在包结构之外使用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.

提前谢谢。

如果您在软件包之外工作,您可以简单地使用Rcpp::sourceCpp(<file>).这将负责为您编译、链接和设计 R 包装器。通过您的文件,我得到:

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