[Rd] Heap access across multiple calls from R to C++

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Wed May 24 08:09:52 CEST 2023


On Wed, 24 May 2023 02:08:25 +0200
<pikappa.devel using gmail.com> wrote:

>   initialize = function() {
> 
>     .C("make_native_obj", self$native_obj)
> 
>   })

> extern "C" void make_native_obj(double *obj) {
> 
>   auto native_obj = new NativeObjStruct();
> 
>   memcpy(obj, &native_obj, sizeof(obj));  
> 
> }

> Is there a better way to do this?

The .Call() interface (where functions take an arbitrary number of
native R objects and return a native R object) combined with external
pointers is likely to be a better approach here:

https://cran.r-project.org/doc/manuals/R-exts.html#External-pointers-and-weak-references

On the R side, the returned SEXP will have class 'externalptr', with
not much to do about it programmatically. C code can additionally
register a finalizer on the object in order to release the memory
automatically after the it is discarded.

-- 
Best regards,
Ivan



More information about the R-devel mailing list