how to inhibit R garbage collection when passing objects to C/C++?

Having some trouble with R's garbage collection, when passing objects to C++.

We have the following scenario:

  1. we create an anonymous function in R, and pass it to C++ code (via .Call())
  2. the C++ code stores the R function object for later use (as a SEXP type) and returns
  3. later on, some other C++ code invokes said R function object using R_tryEval()

Between steps 2 and 3, the R function object appears to get garbage-collected by R. This leads to a crash because R_tryEval() tries to execute something that no longer represents a valid R function object. That's fair, as we haven't done anything to tell R that the function object is still in use...

With that in mind:

  • is there a way, from the C++ code, to mark the R function object as being in-use (such that it doesn't get gc'd)?
  • or is there a safe way to duplicate the R function object, within the C++ code, and manually dispose of it after we invoke R_tryEval()?

(As far as I understand, the PROTECT()/UNPROTECT() macros are not an option here because those are supposed to balance out within the same scope. As in, we can't call PROTECT() when the function is first passed to C++ and then later call UNPROTECT() after it has been executed.)

Answers


I think you're looking for

/* preserve objects across GCs */
void R_PreserveObject(SEXP);
void R_ReleaseObject(SEXP);

in the R_internals.h header.


Need Your Help

Creating a formula in a Rails view?

ruby-on-rails ruby-on-rails-3 logic formula

I would like to create a small formula in my view/home page. Basically it should say if current user signed in (got that part right) AND USER CREATED A REGISTRY = TRUE then this

Upload large file in background (service restarting when the app closed)

android service upload large-files large-file-upload

I would like to upload large files (~10 - 100Mb wifi or mobile network), but in background, because the user maybe will leave the app and later the system will close the app (if not enoguh memory) I