title: how to inhibit R garbage collection when passing objects to C/C++?
body: <p>Having some trouble with R's garbage collection, when passing objects to C++.</p>
  
  <p>We have the following scenario:</p>
  
  <ol>
  <li>we create an anonymous function in R, and pass it to C++ code (via <code>.Call()</code>)</li>
  <li>the C++ code stores the R function object for later use (as a <code>SEXP</code> type) and returns</li>
  <li>later on, some other C++ code invokes said R function object using <code>R_tryEval()</code></li>
  </ol>
  
  <p>Between steps 2 and 3, the R function object appears to get garbage-collected by R. This leads to a crash because <code>R_tryEval()</code> 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...</p>
  
  <p>With that in mind:</p>
  
  <ul>
  <li>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)?</li>
  <li>or is there a safe way to duplicate the R function object, within the C++ code, and manually dispose of it after we invoke <code>R_tryEval()</code>?</li>
  </ul>
  
  <p>(As far as I understand, the <code>PROTECT()</code>/<code>UNPROTECT()</code> macros are not an option here because those are supposed to balance out within the same scope.  As in, we can't call <code>PROTECT()</code> when the function is first passed to C++ and then later call <code>UNPROTECT()</code> after it has been executed.)</p>