[Rcpp-devel] Alternative way of calling R functions within C++
Kevin Ushey
kevinushey at gmail.com
Wed Aug 3 21:34:08 CEST 2016
The simplest demonstrating example I can think of:
---
#include <Rcpp.h>
using namespace Rcpp;
struct A { ~A() { Rprintf("~A()"); } };
// [[Rcpp::export]]
void ouch() {
A a;
Rf_error("ouch!");
}
/*** R
ouch()
*/
---
Call 'Rcpp::sourceCpp()' on that and you'll see:
> Rcpp::sourceCpp('~/Desktop/Untitled.cpp')
> ouch()
Error in ouch() : ouch!
Note that the destructor was not called. Replace `Rf_error` with
`Rcpp::stop` and you will see the destructor is called.
It's possible that you won't have a memory leak per-se (if the memory
is all allocated on the stack, maybe the runtime still knows to just
clear the entire stack after something like this) but not running
destructors is definitely a big problem.
Cheers,
Kevin
On Wed, Aug 3, 2016 at 12:22 PM, Dirk Eddelbuettel <edd at debian.org> wrote:
>
> On 3 August 2016 at 11:38, George Vega Yon wrote:
> | Thanks for the quick reply! What kind of errors are we talking about? I a new
> | run I explicitly caused an error by passing a character vector, and had no
> | memory leak (using Valgrind):
> |
> | cppFuncall(letters, fun)
> | Error in cos(x[1]) : non-numeric argument to mathematical function
> |
> | If its not too much to ask, could you give an explicit example in which that
> | happens (memory leak)? Just trying to learn here!
>
> You are misreading what Kevin said. You short ten-line example runs fine.
> We are not saying it has an error.
>
> What Kevin explained to you is that in the context of larger programs,
> possibly with inputs you don't know yet, some errors may occur. And both
> Rcpp:Function() and Rcpp::stop() can recover from that.
>
> Your example cannot. So by all means use it as a small (local) script if the
> few milliseconds matter to you. But think twice about using it in a larger
> context, or about promoting it as a general solution, and understand why we
> can't put it into Rcpp as is.
>
> Hth, Dirk
>
> --
> http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org
More information about the Rcpp-devel
mailing list