rcpp 函数调用另一个 rcpp 函数 [英] rcpp function calling another rcpp function

查看:67
本文介绍了rcpp 函数调用另一个 rcpp 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我猜这是一个简单的问题,但我是 Cpp 的新手,并且被卡住了.

I'm guessing this is an easy question, but I'm new to Cpp, and am stuck.

我在 R 中创建了一个函数,使用 Rcpp 和:

I've created a function in R, using Rcpp and:

// [[Rcpp::export]]

我可以在 R 中调用该函数并且它按预期工作.我们称之为F1.

I can call the function in R and it works as intended. Let's call it F1.

接下来,我想使用调用第一个函数的 Rcpp 创建另一个函数 F2.我使用标准函数调用语言(即 F1(arguments)),当我使用 sourceCpp() 时,它通过 R 编译得很好.

Next, I want to create another function, F2, using Rcpp which calls the first function. I use standard function call language (i.e., F1(arguments)), and it compiles fine through R when I use sourceCpp().

但是当我尝试在 R 中调用 F2 时,我得到:

But when I try to call F2 in R, I get:

.Primitive(".Call")(

Error in .Primitive(".Call")(

缺少 F2

第一个 .cpp 文件包含

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double F1(NumericVector a) {
  int n = a.size();
  double result=0;  // create output vector
  double ss = 0;

  for(int i = 0; i < n; ++i) {
    ss += pow(a[i],2);
  }

  result = ss;
  return result;
}

以下内容在另一个 .cpp 文件中.

The following is in another .cpp file.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double F2(NumericVector a) {
  double result=0;

  result = F1(a);

  return result;
}

推荐答案

只需将两个函数放在同一个 .cpp 文件中,或者开始处理一个包.

Just put both functions in the same .cpp file, or start working on a package.

如果你坚持使用单独的 .cpp 文件,那么 F2 不知道 F1.您可以将 F1 作为 R 函数回调,但这不会那么有效,您将不得不处理将输出转换为双精度等...

If you stick to separate .cpp files, then F2 does not know about F1. You can call back F1 as an R function, but that's not going to be as efficient and you will have to deal with converting outputs to a double, etc ...

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double F2(NumericVector a) {
  double result=0;

  // grab the R function F1
  Function F1( "F1" ) ; 
  result = as<double>( F1(a) );

  return result;
}

但真正创建一个包或将所有函数放在同一个 .cpp 文件中.

But really create a package or put all your functions in the same .cpp file.

这篇关于rcpp 函数调用另一个 rcpp 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆