[英]Instantiate a module in OCaml dynamically
I have several modules implementing the same interface. 我有几个模块实现相同的接口。 I want to load only one of this module depending on one argument given on the command line.
我只想根据命令行上给出的一个参数加载该模块之一。
I was thinking to use first-class module but the problem is that I want to execute some functions before that the module is instanciated. 我当时在考虑使用一流的模块,但是问题是我想在实例化模块之前执行一些功能。
For the moment I have this : 目前,我有这个:
module Arch = (val RetrolixAbstractArch.get_arch() : RetrolixAbstractArch.AbstractArch)
let get_arch () =
let arch = Options.get_arch() in
if arch = "" then
Error.global_error "During analysis of compiler's architecture"
"No architecture specified"
else
if arch = "mips" then
( module MipsArch : AbstractArch)
else
Error.global_error "During analysis of compiler's architecture"
(Printf.sprintf "Architecture %s not supported or unknown" arch)
But since the command line is not parsed yet, Options.get_arch
give me the empty string. 但是由于尚未解析命令行,
Options.get_arch
给了我空字符串。
I would like to realize the command line parsing before that this function is executed (without adding the parssing in the function). 我想在执行此功能之前实现命令行解析(不在函数中添加解析)。 Is it possible ?
可能吗 ? Should I find an other way to achieve this ?
我是否应该找到其他方法来实现这一目标?
It is possible, but you must use local modules. 可以,但是必须使用本地模块。 This is a minor issue, that basically requires only few refactoring.
这是一个小问题,基本上只需要很少的重构。
let arch_of_name = function
| "mips" -> (module MipsArch : AbstractArch)
| "arm" -> (module Arm)
| _ -> invalid_arg "unknown arch"
let main () =
...
let arch_name = get_arch () in
let module Arch = (val arch_of_name arch_name) in
(* here you can use module Arch as usual *)
Another approach is to functorize your modules with arch structure and instantiate your functors as soon as you know the architecture. 另一种方法是使用拱结构对模块进行功能化,并在知道架构后立即实例化函子。 You can see a full fledged example here (see function
target_of_arch
that creates first-class module for particular architecture). 您可以在此处看到完整的示例(请参见为特定体系结构创建一流模块的函数
target_of_arch
)。
If your AbstractArch
interface doesn't contain type definitions, then you can use other abstractions instead of modules: records of functions or objects. 如果您的
AbstractArch
接口不包含类型定义,则可以使用其他抽象代替模块:函数或对象的记录。 They may work more smoothly, and may even allow you to overload the arch instance dynamically (by making the arch
instance to be a reference, although I wouldn't suggest this, as it is quite unclean, imo). 它们可能会更平稳地工作,甚至可能允许您动态地使
arch
实例过载(通过将arch
实例作为参考,尽管我不建议这样做,因为imo不太干净,但我不建议这样做)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.