If I define a function in R, I can save the function object using the save function. Then I can load that function object using the load function and use it directly. However, if I have a rcpp function, and if I try to save the compiled version and load it back to the memory, I can no longer use that function object directly. Is this even possible? The reason I ask is because it takes a while to compile the function, and if there is a way to avoid that cost every time I launch an R environment, that will be great. Thanks!
Asked
Active
Viewed 899 times
1 Answers
15
No, in general you cannot serialize (and hence save) a function compiled with cxxfunction()
or sourceCpp()
. You need to freshly compile it, unless you place it in a package. Which is why packages are the way to go to really install your compiled code beyond quick experimentation.

Dirk Eddelbuettel
- 360,940
- 56
- 644
- 725
-
3Pleasure. You may choose to 'accept' this answer by selecting the tickmark only you as the person asking it sees. – Dirk Eddelbuettel Mar 07 '13 at 01:03
-
Hi Dirk, can you point me to how you would place it in a package? I have an already compiled function (as returned by sourceCpp) that I would like to reuse later without recompiling... – BenoitLondon May 13 '21 at 10:59
-
I guess you mean putting the c++ code inside a package using Rcpp? I m looking for alternatives as my use case is I have a package A with a function A::factory() that returns a function defined in rcpp and I want to use these functions outside this package (or in another package). Is there any trick to achieve that? – BenoitLondon May 13 '21 at 11:11
-
For example, couldn't I reuse the example.so file with dyn.load(example.so) in my other code/package? – BenoitLondon May 13 '21 at 15:05
-
Please consider stopping to abuse the comment section of a eight year old (!!) question. The topic has been discussed copious times here and on the rcpp-devel list (that is open to you too so maybe sign up and post there) so I suggest you just trust R Core that the _best_ portable way for _compiled code_ really is a package. Code using Rcpp is no different. To R, it is 'just object code' and you (generally) can't just sling that around like a text file. – Dirk Eddelbuettel May 13 '21 at 15:19