如果你有int myfunc(struct mystruct **context)
这样的函数,那么在C中
OCaml外国签名将是
type mystruct
let mystruct : mystruct structure typ = structure "mystruct"
let myfunc = foreign "myfunc" (ptr (ptr mystruct) @-> returning int)
问题是如何调用该函数?我们不能addr (addr mystructinstance)
,所以代码不会编译:
let inst = make mystruct in
let res = myfunc (addr (addr inst))
答案 0 :(得分:4)
ctypes的内存模型与C紧密匹配,因此您需要编写的代码将与您在C中编写的内容相匹配。您对addr (addr mystructinstance)
生病的类型是正确的,即因为它对应于&(&mystructinstance)
,这在C中没有任何意义。
在C中,您可能会写出类似的内容:
mystruct *p = NULL;
int err = myfunc(&p);
if (err == ok) {
// p has now a usable value for the rest of the API
}
ctypes中的等效代码将是
let p_addr = Ctypes.allocate (ptr mystruct) (from_voidp mystruct null) in
let err = myfunc p_addr in
(* check err *)
let p = !@ p_addr in
(* do things with p, typed mystruct structure ptr *)