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...?).
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.
In .cpp
file:
extern "C" {
void RHello() {
Rprintf("Hello.\n");
R_FlushConsole();
R_ProcessEvents();
}
}
Call in R:
.Call("RHello").
This crashes R.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With