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@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to