我有一个关于在包结构之外使用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
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在包的结构内部时有效.我们知道,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
Run Code Online (Sandbox Code Playgroud)
编译成功发生,未发出警告消息.通过这种方式,生成了test.o和test.so文件.已经在R中,使用.Call界面,我做了:
dyn.load("test.so")
my_function <- function(x){
.Call("soma2",x)
}
Run Code Online (Sandbox Code Playgroud)
尝试使用该my_function ()函数时,会发生错误,指出soma2不在加载表中.有没有办法在RcppExports.cpp包的框架外创建文件?我想正确的一个是编译代码RcppExports.cpp而不是test.cpp.
提前致谢.
如果您在包装外工作,您可以简单地使用Rcpp::sourceCpp(<file>).这将负责编译,链接和为您提供R包装.有了你的文件,我得到:
> Rcpp::sourceCpp("test.cpp")
> soma2(1:5)
[1] 15
Run Code Online (Sandbox Code Playgroud)