Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Question about register_global_root
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Maas-Maarten Zeeman <maas@w...>
Subject: Re: [Caml-list] Question about register_global_root
Hello,

I'm by far no Caml expert, but it works pretty well for me in 
OcamlExpat, an OCaml wrapper for Expat I wrote a while back. I use a 
malloced value to store a pointer to a tuple, which is used to store 
event handlers (ocaml functions).

This is what I did:

  /* Malloc a value for a tuple which will contain the callback
   * handlers and register it as global root.
   */
  handlers = (value *) malloc(sizeof(value));
  register_global_root(handlers);

  *handlers = alloc_tuple(NUM_HANDLERS);
  for(i = 0; i < NUM_HANDLERS; i++) {
    Field(*handlers, i) = Val_unit;
  }

One thing to keep in mind is that you have to be really careful, and use 
the right CAMLxxxx macro in the right place, otherwise things start 
crashing at seemingly random times. The reason for this is that the 
global root will correctly stay at the same memory location, but any 
ocaml values stored in the root can move during a garbage collection 
cycle. If you do not use the CAMLxxxx macro's correctly the values will 
change, and move in the middle of your c-function, which almost always 
results in a crashing program.

It is very easy to make mistakes here, but there is a way to (sort of) 
test if your c-extension behaves correctly. If you call "Gc.full_major 
()" in your tests you will know almost instantly if there is a problem 
related to garbage collection, and possible incorrect use of CAMLxxxx 
macros (at least that is the idea).

Regards,

Maas

> Hi Caml experts,
> We are using register_global_root to register addresses in the malloc'd
> C heap that contain Caml values.  We noticed that register_global_root
> (comment below) expects a global C variable, but we assumed that it 
> should
> work with malloc'd addresses as well.  Is there any reason that it 
> would not?
>
> /* [register_global_root] registers a global C variable as a memory root
>    for the duration of the program, or until [remove_global_root] is
>    called. */
>
> We are getting (somewhat random) core dumps after calling the same Caml
> function repeatedly on the same Caml value (which is referenced
> from the C heap).
>
> Thanks,
> Mary




-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners