Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R package with c++ (without Rcpp)

Tags:

c++

package

r

I am trying to build an R package with c++ without using Rcpp (I know Rcpp is working wonderfully). I have read a couple of R package tutorials and briefly read the Writing R Extensions. Below example 1) is working but example 2) crashes R. I want to know why this is happening (Is there any prerequisite steps to write functions for R etc...?).

Example 1

In .cpp file

extern "C" {

  SEXP add(SEXP a, SEXP b) {

    SEXP result = PROTECT(allocVector(REALSXP, 1));

    REAL(result)[0] = asReal(a) + asReal(b);

    UNPROTECT(1);

    return result;

  }

}

Call in R:

.Call("add", 3.0, 2.0).

This example works.

Example 2

In .cpp file:

extern "C" {

  void RHello() {

    Rprintf("Hello.\n");

    R_FlushConsole();
    R_ProcessEvents();

  }

}

Call in R:

.Call("RHello"). 

This crashes R.

like image 488
user8623983 Avatar asked Nov 07 '22 16:11

user8623983


1 Answers

The signature of the function is wrong in the second case (void return value), it needs to return an SEXP object. Even if that's just R_NilValue.

I hope you have a good reason for not using Rcpp.

like image 193
DaBookshah Avatar answered Nov 14 '22 20:11

DaBookshah