[Rd] PROTECT and OCaml GC.

From: Guillaume Yziquel <guillaume.yziquel_at_citycable.ch>
Date: Sun, 29 Nov 2009 00:50:52 +0100


Hello.

In the writing of my OCaml-R binding, I'm sort of confused when it comes to the use of the PROTECT and UNPROTECT macros.

Basically, I have C stub functions that are in charge of calling R for everything. Here's a simple example:

> CAMLprim value r_findvar (value symbol) {
> /* The findVar function is defined in envir.c. It looks up a symbol
> in an environment. */
> CAMLparam1(symbol);
> CAMLreturn(Val_sexp(findVar(Sexp_val(symbol), R_GlobalEnv)));
> }

This simply makes a call to findVar and returns the value to Objective Caml. It seems to me that I should be writing:

> CAMLprim value r_findvar (value symbol) {
> /* The findVar function is defined in envir.c. It looks up a symbol
> in an environment. */
> CAMLparam1(symbol);
> SEXP e;
> PROTECT(e = findVar(Sexp_val(symbol), R_GlobalEnv));
> CAMLreturn(Val_sexp(e));
> }

However, as OCaml has its own GC, I'm wondering where to put UNPROTECT. Many codes I see on the net UNPROTECT the value just after it has been protected. The rationale, it seems, is that the value is at risk only a short timeframe after it has been created.

This seems rather curious to me, and I'm wondering if I should not rather UNPROTECT the value at the moment OCaml's GC says the value is not needed anymore.

Please tell me which option I should go forward with.

(I'll assume for now that OCaml is monothreaded. I do not believe that R itself is thread-safe, so I'll first handle this monothreaded case.)

All the best,

-- 
      Guillaume Yziquel
http://yziquel.homelinux.org/

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Sat 28 Nov 2009 - 23:53:30 GMT

This archive was generated by hypermail 2.2.0 : Sun 29 Nov 2009 - 01:00:51 GMT