Loading ...
Sorry, an error occurred while loading the content.

5854Re: "ocaml_beginners"::[] object finalization

Expand Messages
  • Richard Jones
    May 2, 2006
    • 0 Attachment
      On Tue, May 02, 2006 at 11:11:55AM +0100, Thierry Martinez wrote:
      > Answering to the following Florent Monnier's question:
      > >> 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"
      > initializer
      > prerr_endline "in initializer";
      > Gc.finalise finaliser self
      > end
      >
      > That seems to work.

      This is my revised version, but I still can't get it to run the
      finaliser ...

      #!/usr/bin/ocamlrun ocaml

      let finaliser obj = obj#finaliser

      let () =
      let obj = object (self)
      method hello = prerr_endline "hello"
      method finaliser = prerr_endline "in finaliser"
      initializer
      prerr_endline "in initializer";
      Gc.finalise finaliser self
      end in

      obj#hello;

      (* cause the object to become unreachable *)
      let obj = () in

      (* call the garbage collector so the object should be finalised *)
      Gc.full_major ();

      prerr_endline "finished GC full major cycle"

      Output:

      $ ./final.ml
      in initializer
      hello
      finished GC full major cycle

      Rich.

      --
      Richard Jones, CTO Merjis Ltd.
      Merjis - web marketing and technology - http://merjis.com
      Team Notepad - intranets and extranets for business - http://team-notepad.com
    • Show all 7 messages in this topic