我们可以将Rcpp与多个C ++函数一起使用吗?

时间:2017-07-25 07:14:49

标签: c++ c r

我用.c语言构建自己的函数。然后,我使用.c来设置R函数来调用.C函数,例如

 tmp <- .C("myfunction",
as.integer(N),
as.integer(n),
as.integer(w1),
as.integer(w2),
as.integer(w3),
PACKAGE = "mypackage")[[3]]

被称为包装R函数。此外,我的功能基于或要求其他.c功能。据我所知,使用Rcpp使其更加灵活和简单,例如:

cppFunction('int add(int x, int y, int z) {
  int sum = x + y + z;
  return sum;
}')

我也知道cppFunction适用于C++语言。但是,我发现.c函数和.c++之间没有太大区别。

我的问题是:我可以将cppFunction与我的.c函数一起使用requurie wraper R函数吗?或者我需要先将.c函数转换为.c++函数?那我的功能所基于的其他功能怎么样?这是否与常规R功能一样?  我的意思是:假设我有两个cppFunction函数myfunc1myfunc2 myfunc2基于myfunc1。然后假设我的第二个cppFunction如下:

cppFunction('int myfunc2(int x, int y, int z) {
      int sum = x + y + z;
      myfunc1 ## do some works here
      return something;
    }')

那会好吗?或者我需要写如下:

cppFunction('int myfunc2(int x, int y, int z) {
      int sum = x + y + z;
      cppFunction('int myfunc2(int some arguments) {## do some works here}
      return something;
    }')

一般情况下如何使用包含多个函数的构建cppFunction

有什么帮助吗?

1 个答案:

答案 0 :(得分:6)

以下是使用外部cpp文件的示例。 这些函数可以在同一个文件中进行交互,但是像其他人一样,你必须使用header来使用其他文件中的函数。 您必须在R。

中可用的任何功能之前使用// [[Rcpp::export]]

(感谢@F.Privé改进代码)

1) 文件cpp:

#include <Rcpp.h>
using namespace Rcpp;



// [[Rcpp::export]]
double sumC(NumericVector x) {
  int n = x.size();
  double total = 0;

  for(int i = 0; i < n; ++i) {
    total += x[i];
  }
  return total;
}

// [[Rcpp::export]]
double meanC(NumericVector x) {
  return sumC(x) / x.size();
}

档案R:

Rcpp::sourceCpp("your path/mean.cpp")
x <- 1:10
meanC(x)
sumC(x)

2) 使用cppfunction的替代方法 。你必须使用包含参数

cppFunction('double meanC(NumericVector x) {
  return sumC(x) / x.size();
}',includes='double sumC(NumericVector x) {
  int n = x.size();
  double total = 0;

  for(int i = 0; i < n; ++i) {
    total += x[i];
  }
  return total;
}')

无论如何,我建议你使用sourceCpp,使用独立文件可以产生更易维护和更干净的代码

3) 使用sourceCPP和多个cpp文件 。您必须使用头文件并为要在其他cpp文件中使用的每个file.cpp执行头文件。

sum.h文件(ifndef防止多重定义)

#include <Rcpp.h>
#ifndef SUM1
#define SUM1

double sumC(Rcpp::NumericVector x);

#endif

sum.cpp(和以前一样)

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sumC(NumericVector x) {
  int n = x.size();
  double total = 0;

  for(int i = 0; i < n; ++i) {
    total += x[i];
  }
  return total;
}

mean.cpp文件  (你必须包括总和标题) #include“sum.h”

#include <Rcpp.h>
#include "sum.h"
using namespace Rcpp;

// [[Rcpp::export]]
double meanC(NumericVector x) {
  return sumC(x) / x.size();
}
相关问题