在 OCaml 的字符串中包含空字符/字节的惯用方法

Idiomatic way to include a null character / byte in a string in OCaml

我正在研究 OCaml Unix 模块,看看它是否会拒绝包含某些字节的字符串,这些字节可能在给定系统调用的上下文中产生令人惊讶的效果并抛出异常。例如。 Unix.create_processprog 参数中的空字节,或 env : string array 参数中的一个字符串中的换行符。

我尝试了几种方法在我的字符串中包含空字节,例如 "/bin/ls[=14=]"(这是字符串文字中的非法转义序列)和 "/bin/ls" ^ string_of_char '[=15=]'(这是非法序列在字符文字中)。最后,我将零转换为一个字符串,然后将一个包含空字符的长度为 1 的字符串与我的字符串连接起来。

module U = Unix;;

let string_of_char ch : string = String.make 1 ch

let sketchy_string = "/bin/ls" ^ string_of_char (char_of_int 0)

let _ = U.create_process sketchy_string [|"ls"|] U.stdin U.stdout U.stderr

向 ocaml 字符串添加空字节的正确方法是什么?

您可以使用通用 "hexadecimal code" 转义序列来写入空字节(或您想要的任何其他字节):

let null_byte = '\x00';;
let sketchy_string = "/bin/ls\x00";;

如需进一步参考,请参阅 Ocaml 手册中涵盖转义序列的部分:http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#escape-sequence