I've had success w/ using a reference counting paradigm in which the outside
memory manager calls UNPROTECT_PTR(R_object_); in its destructor.

So, in my case (using c++ ) if objects are allocated on the heap, which
allocate R objects as their backend storage, I don't have to worry about out
of order UNPROTECT calls b/c UNPROTECT_PTR will just put the objects that
c++ destroys on the gc list.

If you are using c as the glue for all your ocaml bindings, they you may
want to have a look at this:
http://github.com/armstrtw/rabstraction

Or the in progress re-write here: http://github.com/armstrtw/RObjects

-Whit


On Sat, Nov 28, 2009 at 6:50 PM, Guillaume Yziquel <
guillaume.yziquel@citycable.ch> wrote:

> 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
>

	[[alternative HTML version deleted]]

