首页 > 解决方案 > RStudio 不断与 Rcpp 崩溃

问题描述

我想了解是什么导致该程序崩溃。我在这里这里这里看到了至少三个相关的问题,但我还没有找到解决这个问题的明确答案,所以这里有一些示例代码来复制这个问题。

R代码:

library(Rcpp)

Rcpp::sourceCpp("myfunction.cpp")

data1      <- rnorm(2000)
data2      <- rnorm(2000)

mydata <- matrix(cbind(data1, data2), nrow=2000, ncol=2)
values <- log(1:6)

for (i in 1:1000) {
  myfunction(values, mydata)
}

C++ 代码:

#include "Rcpp.h"
#include "math.h"
using namespace Rcpp;

// [[Rcpp::export]]
double myfunction(const NumericVector& theta, const NumericMatrix& data) {

  double ans = 0;

  int theta_size = theta.length();
  NumericVector mytheta(theta_size);

  int data_size = data.nrow();
  NumericMatrix mat(data_size, 2);

  for (int i = 0; i < theta_size; i++) {
    mytheta(i) = exp(theta(i));
  }

  if ( true ) {  // Flow control

    for (int i = 0; i < data_size; i++) {
      mat(i, 1) = pow(data(i-1, 1), 2) + mytheta(1)*mat(i-1, 1);
      ans = ans + 1;
    }

    for (int i = 0; i < data_size; i++) {
      mat(i, 2) = pow(data(i-1, 2), 2) + mytheta(4)*mat(i-1, 2);
      ans = ans + 1;
    }

  }

  Rcout << "Ok!\n";

  return ans;
}

至少在我第一次使用时一切正常myfunction(),但是在 R for 循环中调用时它会崩溃。我重新安装了 R、Rtools 和 RStudio(在 Windows 上),看看安装是否有问题,但我仍然面临同样的问题。

这使得 R 和 C++ 之间的无缝集成不像我最初想象的那样无缝,而且由于我发现我不是唯一一个面临这个问题的人,看起来我们在开始时都犯了一些明显的错误Rcpp(至少在 RStudio 上),但它是什么?

本质上,我想确保我没有在这里遗漏一些完全明显的东西,因为到目前为止我所看到的所有答案似乎都暗示确实如此。

注意:这是我一直在使用 Rcpp 测试的较长功能的缩短版本,原始版本在我调用它的前几次似乎工作正常,但它最终也崩溃了。

更新:删除 rm(),哎呀。

标签: c++rrcpp

解决方案


for (int i = 0; i < data_size; i++) {
  mat(i, 1) = pow(data(i-1, 1), 2) + mytheta(1)*mat(i-1, 1);
  ans = ans + 1;
}

i == 0,您尝试访问data(-1, 1)并且事情从那里变成梨形。它在你第一次运行时没有崩溃的事实只是意味着你很幸运(或不走运,因为它诱使你产生一种虚假的自信感)。


推荐阅读