Skip to content
Prev 61287 / 63424 Next

Object are not destroy while using error (Rf_error)

On 1/21/23 16:55, Antoine Lucas wrote:
The problem is that Rf_error() uses a long jump, which unwinds the C++ 
frames without calling destructors. Using the C API of R from C++ code 
is tricky because of this incompatibility of C long jumps with C++ 
destructors.

Technically, you need to protect all calls from C++ to R against long 
jumps. There is an API for that, see R_UnwindProtect in 6.12 of "Writing 
R Extensions". So, your wrapper will get called in case of a long jump 
and will handle it in a way compatible with your C++ frames (possibly by 
throwing a C++ exception).

Similarly, you should not throw C++ exceptions over R frames on the 
stack, because R's meta-data about long jump targets on its stacks would 
go out of sync, causing a crash later. You again would have to convert 
C++ exceptions to long jumps.

So, in your example where you use the R API to only trigger an R error, 
you could instead throw a C++ exception, and catch it later, below all 
your C++ code but before unwinding could potentially reach R frames. And 
there you could call Rf_error().

Best
Tomas

(this is related: 
https://blog.r-project.org/2019/03/28/use-of-c-in-packages )