4

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

  • 函数 1 = 线性插值.cpp
  • 函数2 = 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 并编写了一个使用 Rcpp 的包我想我也阅读了正确的部分,但我没有明白。

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

对不起,但我真的被困住了。

谢谢和最好的问候

尼科

4

1 回答 1

3

也许您应该制作另一个文件,一个头文件.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文件)中,翻译单元是两个C++函数相互看到的重要东西。它们必须在同一个 cpp 文件中,或者您必须使用头文件。

于 2015-07-14T12:55:23.203 回答