Is it possible to nest Rcpp
functions in each other?
I have a dummy example right here:
cppFunction(
'int add3(int x) {
return x 3;
}')
cppFunction(
'int add4(int x) {
return add3(x) 1;
}')
add3(2)
This does not work. How can I make this work?
Edit: Okay, so I followed Dirk's advice and now I have a test.cpp
file:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
int add3(int x) {
return x 3;
}
// [[Rcpp::export]]
int add4(int x) {
return add3(x) 1;
}
Which I load in R with sourceCpp("test.cpp")
. Now I can use both functions in R and they work although one function calls the other function.
CodePudding user response:
The answers to your question get a little technical quickly, but are all provided in the Rcpp Attributes vignette, and have been for a long time.
First off, you are more-or-less misusing cppFunction()
. It is made for quick and simple one-off function tests. Not for writing "infrastructure" or more complex code. For which you should use sourceCpp()
, or better still, use a package.
If you switch you code to sourceCpp()
and the [[Rcpp::export]]
tag you will notice (in verbose=TRUE
mode, or in package building) that the exported functions get 'transliterated' into other functions that R calls.
So yes you can nest functions, as you can in C / C . Nothing is taken from you. But you cannot call the inner, nested function from R but that is possible with the API offered to us by R and which we use (and free you from interfacing directly). It only has SEXP .Call(functionanme, SEXP a, SEXP b,...)
as an interface. I.e. a different signature.
But on the C / C you can nest, provided you compile your code differently.