[Rcpp-devel] Creating an R interface to non-copyable C++ class

Cris Luengo cris.l.luengo at gmail.com
Thu Apr 12 07:54:59 CEST 2018


> On Apr 11, 2018, at 19:14, Dirk Eddelbuettel <edd at debian.org> wrote:
> 
> On 11 April 2018 at 17:19, Cris Luengo wrote:
> | Ideally, an R variable would hold on to this pointer (with or without the
> | `std::unique_ptr` around it), and delete the object when it is cleared (or
> | garbage collected, or whatever R uses). Is this possible?
> 
> Yes. I have done things like that with eg interfaces to DB engines and alike.
> 
> One approach is to create a singleton class, and have it shield the
> std::<unique_ptr>.  You can add an init() function that sets things up,
> possibly with arguments from R (standard string, int, ... whatever is
> needed).  And then add worker functions to set, get, change, ...  whatever
> you need give the pointer.  You can add an explicit wind-down too to log,
> lock, close, ... whatever you have to do with the resource.

A singleton class is equivalent to a static instance. Basically you're
suggesting a static `std::unique_ptr` that will own the object when created.
The R interface then has functions that create, modify, query and destroy
the object pointed to by the static pointer.

That could absolutely work in this case, I don't need there to be more than
one object of this class at the time. And it seems a simple approach. I will
give this a try in the morning.

> The way R thinks about this is that _it_ owns everything, and Rcpp makes
> getting things back and forth _using the R memory system and its lifetime /
> reference count control_ fairly easy.

Yes, that makes sense. But somehow it is not easy to transfer ownership
of an object to R. There needs to be a new object created that it can own?

Many thanks!
Cris.




More information about the Rcpp-devel mailing list