【问题标题】:Using a c++ function in an other c++ function (inside a R Package with Rcpp)在其他 c++ 函数中使用 c++ 函数(在带有 Rcpp 的 R 包中)
【发布时间】:2015-07-14 12:41:48
【问题描述】:

我尝试创建一个 R 包(使用 Rcpp)。 一切正常。但是现在我写了一个 c++ 函数,我想在另一个 c++ 文件中调用它。 所以在 /src 中有:

  • function1 = linearInterpolation.cpp
  • function2 = getSlope.cpp

让我们以function1为例,它只是在特定位置的两点之间进行线性插值。

#include <Rcpp.h>

using namespace Rcpp;

//' @name linearInterpolation
//' @title linearInterpolation
//' @description Twodimensional linearinterpolation for a specific point
//' @param xCoordinates Two x coordinates
//' @param yCoordinates Coresponding two y coordinates
//' @param atPosition The Point to which the interpolation shall be done
//' @return Returns the linear interpolated y-value for the specific point
//' @examples
//' linearInterpolation(c(1,2),c(1,4),3)
//'
//' @export
// [[Rcpp::export]]
double linearInterpolation(NumericVector xCoordinates, NumericVector yCoordinates, double atPosition) {

  // start + delta y / delta x_1 * delta x_2
  return yCoordinates[1] + getSlope(xCoordinates, yCoordinates) * (atPosition - xCoordinates[1]);

}

并且斜率在不同的函数(文件)中计算。

#include <Rcpp.h>

using namespace Rcpp;

//' @name getSlope
//' @title getSlope
//' @description Calculates the slopes between two points in 2Dimensions
//' @param xCoordinates Two x coordinates
//' @param yCoordinates Coresponding two y coordinates
//' @return Returns the slope
//' @examples
//' getSlope(c(1,2),c(1,4),3)
//'
//' @export
// [[Rcpp::export]]
double getSlope(NumericVector xCoordinates, NumericVector yCoordinates) {
  return (yCoordinates[1] - yCoordinates[0]) / (xCoordinates[1] - xCoordinates[0]);
}

我对 Rcpp 或 c++ 没有任何深入的了解。我阅读了 Vignette 和 Writing a package that uses Rcpp 我想我也阅读了正确的部分,但我没有明白。

为什么 getSlope 函数在另一个函数中不“可见” - 因为它们都在同一个包中。 如何在其他文件中使用 getSlope?

对不起,我真的卡住了。

感谢和最好的问候

尼哥

【问题讨论】:

  • 你必须link这两个文件。将它们放在同一个文件中会更容易。
  • 请告诉我们您收到的错误信息。简单地说“功能不可见”是不够的。 “可见”是什么意思?
  • 嗨 Verena,我不想将它们放入同一个文件中。我最终会陷入多种功能的混乱局面。但谢谢,我会通过你的链接阅读。嗨亚伦,当然,对不起。我得到的错误是:'getSlope' 没有在这个范围内声明

标签: r rcpp r-package


【解决方案1】:

也许你应该再做一个文件,一个头文件.hpp,然后把它放进去:

#include <Rcpp.h>
using namespace Rcpp;
double getSlope(NumericVector xCoordinates, NumericVector yCoordinates);

或者,更好的是,

#include <Rcpp.h>
double getSlope(Rcpp:: NumericVector xCoordinates, Rcpp:: NumericVector yCoordinates);

并将#include"myheader.hpp" 放在两个 cpp 文件的顶部。这是为了声明这个函数,以便两个 cpp 文件都可以看到它。


...因为它们都在同一个包中

仅仅因为两个东西在同一个 R 包中,并不意味着它们在同一个 C++ 翻译单元(即 cpp 文件)中,而 translation unit 是两个 C++ 函数相互查看的重要内容。它们必须在同一个 cpp 文件中,或者您必须使用头文件。

【讨论】:

  • 好的,这改变了一些东西......现在我遇到了更多错误。在 .hpp 文件中: - 在此范围内未声明 2x 数值向量 - 在初始化程序中将表达式列表视为复合表达式 - 在 getSlope.cpp 中先前声明的“双 getSLope”: - 将双 getSlope 重新声明为不同类型的符号 抱歉,现在我完全迷失了......
  • 我忘记了一些事情,现在我已经更新了答案。您的头文件还应包括 #include &lt;Rcpp.h&gt; 作为其第一行。这是为了让头文件“理解NumericVector 是什么。另外,using namespace Rcpp;
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2022-07-12
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多