5854Re: "ocaml_beginners":: object finalization
- May 2, 2006On Tue, May 02, 2006 at 11:11:55AM +0100, Thierry Martinez wrote:
> Answering to the following Florent Monnier's question:This is my revised version, but I still can't get it to run the
> >> I would like that a method of an object to be called when this object is
> >> finalized. Is it possible ?
> Richard Jones wrote:
> > let () =
> > let obj = object (self)
> > method hello = prerr_endline "hello"
> > method finaliser _ = prerr_endline "in finaliser"
> > initializer
> > prerr_endline "in initializer";
> > Gc.finalise self#finaliser self
> > end in
> I am discovering the Gc module thanks to your message. In the OCaml
> documentation, a warning says that the registered callback has to be
> out of the scope of the considered value, such that its closure
> doesn't capture the value. Your code could be rewritten as:
> let finaliser obj = obj#finaliser
> let obj = object (self)
> method hello = prerr_endline "hello"
> method finaliser _ = prerr_endline "in finaliser"
> prerr_endline "in initializer";
> Gc.finalise finaliser self
> That seems to work.
let finaliser obj = obj#finaliser
let () =
let obj = object (self)
method hello = prerr_endline "hello"
method finaliser = prerr_endline "in finaliser"
prerr_endline "in initializer";
Gc.finalise finaliser self
(* cause the object to become unreachable *)
let obj = () in
(* call the garbage collector so the object should be finalised *)
prerr_endline "finished GC full major cycle"
finished GC full major cycle
Richard Jones, CTO Merjis Ltd.
Merjis - web marketing and technology - http://merjis.com
Team Notepad - intranets and extranets for business - http://team-notepad.com
- << Previous post in topic Next post in topic >>