title: R: How to write interruptible C++ function, and recover partial results
body: <p>We are writing an R package, the core of which is written in C++ and basically consists of one long-running loop:</p>
  
  <pre><code>void core_func(double* data)
  {
      while (!done)
      {
          // update 'data'
      }
  }
  </code></pre>
  
  <p>The call is made using R's <code>.C</code> mechanism:</p>
  
  <pre><code>ans &lt;- .C("core_func", data = as.double(data))$data
  </code></pre>
  
  <p>We would like for the user to be able to interrupt the function, and to recover the partial results (i.e., contents of <code>*data</code> at point of interrupt).</p>
  
  <p><strong>Question:</strong>  Is this in any way possible?</p>
  
  <p>Our efforts to come up with a solution have so far produced <a href="http://permalink.gmane.org/gmane.comp.lang.r.devel/27627" rel="noreferrer">this post</a>, which - if interpreted correctly - gives an indication on how to cleanly exit from the loop.</p>
  
  <pre><code>void core_func(double* data)
  {
      while (!done &amp;&amp; !checkInterrupt())
      {
          // update 'data'
      }
  }
  </code></pre>
  
  <p>What we haven't figured out, is how to pass the partial results back to the caller (aka. R user).</p>
  
  <p><strong>Solution:</strong>  It seems the solution was right in front of us all this time.  The approach proposed by Simon Urbanek in the abovementioned post (original post <a href="https://stat.ethz.ch/pipermail/r-devel/2011-April/060702.html" rel="noreferrer">here</a>) covers all the bases.  Making use of the <code>checkInterrupt()</code> function, the C++ code can be designed to exit cleanly upon a user interrupt; and, most importantly, control is then handed back to the calling <code>.C</code> function in R, which can return the (partial) results in an orderly manner.</p>
  
  <p>Thanks to @Jeroen for clearing things up (and for the hint about <a href="https://github.com/search?utf8=%E2%9C%93&amp;q=user%3Acran%20R_CheckUserInterrupt%20language%3Ac%2B%2B&amp;type=Code&amp;ref=searchresults" rel="noreferrer">searching for code</a> in <a href="http://www.r-pkg.org/" rel="noreferrer">METACRAN</a>)!</p>
  
  <p><em>Note concerning the Update in Jeroen's answer:</em>  We wish to keep the C++ code R-agnostic (precluding a dependency on Rcpp).</p>