有时人们希望使用ocaml模块作为接口来编写某些C代码的绑定,或者优化C中对象的某些方法。但是,无法在对象之前定义外部函数,因为它需要对象的类型并且无法定义对象,因为它需要调用外部函数。
一种解决方案是使用递归模块,但这很容易使源大小变得琐碎,变得非常难以理解。外部函数也进入模块命名空间,需要再次隐藏。那么什么是更短,更易读的解决方案?
答案 0 :(得分:0)
我想出了如何使用第一类模块直接在一个对象中定义外部函数。第一个需要第一个类模块使用的模块类型。这是通用的,可以反复用于任何类型的外部功能:
module type External = sig
type e
val stub : e
end
之后,可以声明这样的外部函数:
class c =
let ext = (module struct
type e = c -> unit
external stub : c -> unit = "stub"
end : External with type e = c -> unit)
in
object(self:'self)
method as_c = (self :> c)
method foo =
let module E = (val ext)
in
E.stub self#as_c
end
或者在方法本身内更加本地化:
class c = object(self:'self)
method as_c = (self :> c)
method foo =
let module E = (val (module struct
type t = c -> unit
external stub : c -> unit = "stub"
end) : External with type t = c -> unit)
in
E.stub self#as_c
end
注意:as_c方法避免(open)自我类型被关闭或转义其范围。