在构建R包时从另一个Rcpp函数调用Rcpp函数

use*_*481 12 r function include package rcpp

我从另一个问题中拿了这个例子.我正在用Rcpp构建一个R包.我有一个像fun1(下面)这样的函数,我想把它放到自己的.cpp文件中.然后我想调用fun1其他函数(如下fun()所示).我想fun1在一个单独的文件中,因为我将从不同.cpp文件中的几个Rcpp函数调用它.是否有某些include语句和我需要做的事情才能使fun1函数在.cppwhere 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);
                           ")
Run Code Online (Sandbox Code Playgroud)

所以对于我的代码,我将有两个.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);
}
Run Code Online (Sandbox Code Playgroud)

第二个.cpp文件:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int fun1( int a1)
{int b1 = a1;
 b1 = b1*b1;
 return(b1);
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*hey 15

两种可能的解决方

"快速而肮脏"的解决方案 - 在您使用它的文件中包含函数声明:

#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);
}
Run Code Online (Sandbox Code Playgroud)

更强大的解决方案:编写声明函数的头文件,然后可以#include在每个文件中使用-ed.因此,您可能fun1.h在同一src目录中有一个头文件:

#ifndef PKG_FOO1_H
#define PKG_FOO1_H

int foo(int);

#endif
Run Code Online (Sandbox Code Playgroud)

您可以使用以下内容:

#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);
}
Run Code Online (Sandbox Code Playgroud)

随着您的进步,您将需要学习更多的C++编程技能,所以我建议您查看其中一本书 ; 特别是,Accelerated C++是一个很好的介绍.