I'm writing an R package in Rust, which communicates with R via its C API interface.
One fundamental question seems tricky to me is the memory management.
So first let me briefly explain how my Rust program communicates with R.
First, on R side, it calls a C dynamic library with .Call(). The C library then is linked to the Rust static library with C compatible ABI.
R scripts is doing some simple works like input validation, and decide which C function to call based on inputs. Then C program passes the calls to underlying Rust functions, which are exposed as C-compatible functions.
It's pretty clear so far, then it gets tricky once Rust has finished computation and needs to send result back.
One option is to directly call Rf_allocXXX functions on Rust side, and store results within it. Then passes the raw pointer of the R object back to C, and then to R.
But it's unclear to me, whether this will result in memory leak.
It seems to me that if Rust calls Rf_allocXXX, the new R objected (SEXP) is created on Rust program's heap memory. When passing the raw pointer out, Rust will not destroy the object. But then what will happen?
Note that the SEXP created by Rust in this way is directly passed back to C and R. There's no re-allocation. So it seems very unclear to me whether this SEXP would be correctly freed by R's GC.
A related question,
What I noticed from Rcpp's source code is, it seems like just calling R's C API for creating its various vectors, which are wrappers of SEXP.
But I'm not yet clear how it deal with memory management. Does it just simply turns the SEXP object back and R will correctly handle GC?