【发布时间】:2017-05-09 03:40:41
【问题描述】:
我正在为一些使用 out-parameter 习惯用法并返回错误代码的 C 函数编写 OCaml 包装器。我一直在使用Ctypes.allocate_n 在OCaml 端分配一个C 数组来包装它们。然后将内容复制到 OCaml 类型中。
我觉得我正在解决Ctypes 或其他模块已经以另一种方式解决的问题,这是一个示例。
gethostname(2) 具有以下类型:
int gethostname(char *name, size_t len);
这里是 out_parameter.mli 用于包装的 gethostname 函数。
val gethostname : int -> [> `Ok of string | `Error of int];;
这是实现
open Core.Std;;
let (@->) = Ctypes.(@->);;
let returning = Ctypes.returning;;
open Foreign;;
let gethostname size =
let size' = Unsigned.Size_t.of_int size in
let c_gethostname =
foreign "gethostname" (Ctypes.ptr Ctypes.char @-> Ctypes.size_t @-> returning Ctypes.int) in
let buf = Ctypes.allocate_n Ctypes.char ~count:size in
let err = c_gethostname buf size' in
match err with
| 0 -> (
`Ok (Ctypes.string_from_ptr buf ~length:size)
)
| _ -> `Error err;;
let main () =
Printf.printf "%s\n" (match gethostname 1000 with
| `Ok hostname -> hostname
| `Error _ -> "error getting hostname");;
let () = main ();;
为了完整起见,我用这个命令编译了out_parameter.native。
$ corebuild -pkg ctypes.foreign out_parameter.native
代码确实有效并返回主机名,去掉了尾随的空字节。
$ ./out_parameter.native
MY-HOSTNAME
$ ./out_parameter.native | sed -e 's/\x0/@/g'
MY-HOSTNAME
【问题讨论】:
标签: ocaml