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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <xavier.leroy@i...>
Subject: Re: [Caml-list] Delaying module initialization
> I think this must have something to do with Dynlink.  The manual
> states:
> 
>   All toplevel expressions in the loaded compilation units are
>   evaluated.

Yes, indeed.  Compilation units loaded at top-level or dynamically via
Dynlink are always loaded and their initialization code executed,
because there is no way for the system to determine whether they'll be
needed later.  Static linking can determine this, and therefore
removes unreferenced units from .cma libraries.

J. Skaller unhelpfully suggests:

> Hassle the ocaml team for generation of shared libraries?

Shared libs will definitely not help here (and elsewhere).  By
definition, linking with a shared lib is like dynamically loading all
units contained in this lib, hence no way to eliminate unneeded ones.
Only static linking can do that.

(As far as "hassling" goes, this will only reinforce my conviction
that shared libraries are useless.  So, don't do that.)

Coming back to Rich Jones' problem, there are two ways to go about
this:

1- Since you're dynamically loading the Caml modules anyway, couldn't
you arrange so that only those you really need are loaded?

2- Instead of doing

        let _ = eval "use LWP::UserAgent"
        let somefun x y = ...

you could implement on-demand evaluation of the "use" bit, e.g.

        let inited = ref false
        let init() =
          if not !inited then begin
            eval "use LWP::UserAgent";
            inited := true
          end
        let somefun x y = init(); ...

Every function needs to be protected by a call to init().  If you
export constants and not just functions, this won't work, of course,
but maybe this doesn't happen too often.

A nicer way to write the above is

        let init = lazy (eval "use LWP::UserAgent")
        let somefun x y = Lazy.force init; ...

Hope this helps,

- Xavier Leroy

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