【发布时间】:2014-06-25 00:22:55
【问题描述】:
我从另一个问题中举了这个例子。我正在用 Rcpp 构建一个 R 包。我有一个像fun1(下)这样的函数,我想将它放入它自己的.cpp 文件中。然后我想用其他函数调用fun1(就像下面的fun() 一样)。我想将fun1 放在一个单独的文件中,因为我要从不同.cpp 文件中的几个Rcpp 函数调用它。是否有某些包含语句和我需要做的事情才能使.cpp 中的fun1 函数可以访问fun() 所在的位置?谢谢你。
library(inline)
library(Rcpp)
a = 1:10
cpp.fun = cxxfunction(signature(data1="numeric"),
plugin="Rcpp",
body="
int fun1( int a1)
{int b1 = a1;
b1 = b1*b1;
return(b1);
}
NumericVector fun_data = data1;
int n = data1.size();
for(i=0;i<n;i++){
fun_data[i] = fun1(fun_data[i]);
}
return(fun_data);
")
所以对于我的代码,我将有两个 .cpp 文件:
#include <Rcpp.h>
using namespace Rcpp;
// I think I need something here to make fun1.cpp available?
// [[Rcpp::export]]
Rcpp::NumericVector fun(Rcpp::NumericVector data1)
{
NumericVector fun_data = data1;
int n = data1.size();
for(i=0;i<n;i++){
fun_data[i] = fun1(fun_data[i]);
}
return(fun_data);
}
还有第二个.cpp 文件:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
int fun1( int a1)
{int b1 = a1;
b1 = b1*b1;
return(b1);
}
【问题讨论】:
-
这真的是 C++ 的基本用法,与 Rcpp 无关。学习使用任何像样的 C++(甚至 C)书籍都会涵盖的通用头文件。
标签: r function include package rcpp