Browse thread
invoke function from its name as string
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Berke Durak <berke.durak@e...> |
| Subject: | Re: [Caml-list] invoke function from its name as string |
Ludovic Coquelle a écrit :
> First, hello everyone as it is my first message to this list ;)
>
> I'm trying to solve this problem:
> I have a module name and function name in string variables,
> and I would like to call this function, like :
> let mod = "MyMod" in
> let fn = "my_fun" in
> what_come_here mod fn
>
> Can this problem be solved?
There is a Turkish saying stating that "There is a solution to every
problem in a democracy"!
So here you go.
Note that since you're asking for a hackish operation, I felt authorized
to use a hackish solution, using Dynlink.
File alpha.ml:
let f () = Printf.printf "Alpha.f\n%!"
--
File foo.ml:
module A = Alpha
let _ = Dynlink.init ()
let call md fn =
let oc = open_out "x.ml" in
Printf.fprintf oc "let _ = %s.%s ()\n" md fn;
close_out oc;
if Sys.command "ocamlbuild x.byte" <> 0 then failwith "Duh";
try
Dynlink.add_interfaces ["alpha"] ["_build"];
Dynlink.loadfile "_build/x.cmo"
with
| Dynlink.Error e ->
Printf.printf "Too bad: %s\n%!" (Dynlink.error_message e)
let _ =
call Sys.argv.(1) Sys.argv.(2)
--
% ocamlbuild.native -tags use_dynlink foo.byte
% ./foo.byte Alpha f
Alpha.f
--
Berke DURAK