我从一个不同的问题中获取了这个例子。我正在用 Rcpp 构建一个 R 包。我有一个类似 fun1
的函数(下图)我想放到自己的.cpp
文件。那我要打fun1
与其他功能(如 fun()
下面做)。我要 fun1
在一个单独的文件中,因为我将从几个不同的 Rcpp 函数中调用它 .cpp
文件。是否有某些包含声明和我需要做的事情来制作 fun1
可在 .cpp
中访问的功能哪里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);
}
最佳答案
两种可能的解决方案:
'quick-and-dirty',解决方案 - 在您使用它的文件中包含函数声明:
#include <Rcpp.h>
using namespace Rcpp;
// declare fun1
int fun1(int a1);
// [[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);
}
更健壮的解决方案:编写声明函数的头文件,然后可以是
#include
-ed 在每个文件中。所以你可能有一个头文件 fun1.h
在同一 src
目录:#ifndef PKG_FOO1_H
#define PKG_FOO1_H
int foo(int);
#endif
然后您可以将其用于以下内容:
#include <Rcpp.h>
#include "fun1.h"
using namespace Rcpp;
// [[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);
}
随着您的进步,您将需要学习更多 C++ 编程技能,因此我建议查看 one of the books here ;特别是,Accelerated C++是一个很好的介绍。
关于r - 在构建 R 包时从另一个 Rcpp 函数调用 Rcpp 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23527719/