简体   繁体   English

如何使用`js_of_ocaml`从`bytes`生成`ArrayBuffer`

[英]How to produce a `ArrayBuffer` from `bytes` using `js_of_ocaml`

I am building a JavaScript library that is implemented in Ocaml and compiled to JavaScript using js_of_ocaml . 我正在构建一个在Ocaml中实现的JavaScript库,并使用js_of_ocaml编译为JavaScript。

One of my Ocaml function returns a string with binary data. 我的一个Ocaml函数返回一个包含二进制数据的string How can I expose that using js_of_ocaml as a ArrayBuffer ? 如何使用js_of_ocaml作为ArrayBuffer公开它?

When you compile to javascript, manipulating binary data in string s is extremely bug prone! 当您编译为javascript时,在string s中操作二进制数据非常容易出错!

The underlying reason is questionable choice of js_of_ocaml : Because javascript strings are encoded in UTF16 whereas OCaml ones are (implicitly) encoded in UTF8, js_of_ocaml tries to navigate in between the 2. Therefore, when it encounters a "character" whose code is > 127, js_of_ocaml converts it which is a disaster if it is, in fact, raw binary data! 根本原因是js_of_ocaml可疑选择:因为javascript字符串是以UTF16编码而OCaml字符串是(隐式地)编码为UTF8, js_of_ocaml尝试在2之间导航。因此,当它遇到代码> 127的“字符”时, js_of_ocaml将它转换为灾难,如果它实际上是原始二进制数据!

The solution is to manipulate bigstring s instead of string s. 解决方案是操纵bigstring而不是string s。 Bigstrings are (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t in raw OCaml but more and more libraries aliases them. Bigstrings是原始OCaml中的(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t但是越来越多的库将它们别名化。 Especially, they are Typed_array.​Bigstring.t in js_of_ocaml (where you can see functions to convert from and to ArrayBuffer ) 特别是,它们是Typed_array.​Bigstring.t中的js_of_ocaml (在这里你可以看到从和转换到ArrayBuffer函数)

If your function does work by magic on string once compiled in javascript, there are translation function in between bigstrings and strings in several places. 如果你的函数在javascript中编译后在字符串上运行魔术,那么在几个地方的bigstrings和字符串之间就有翻译功能。 For example the bigstring library: http://c-cube.github.io/ocaml-bigstring/ but these functions are also available in Lwt_bytes of lwt 例如,bigstring库: http://c-cube.github.io/ocaml-bigstring/但这些功能也可以在Lwt_bytesLWT

You can see an other question on the same subject (including ways to manipulate OCaml string in javascript while not touching them at all using gen_js_api ) at https://discuss.ocaml.org/t/handling-binary-data-in-ocaml-and-javascript/1519 您可以在https://discuss.ocaml.org/t/handling-binary-data-in-ocaml上查看关于同一主题的其他问题(包括在javascript中操作OCaml字符串的方法,而不是使用gen_js_api完全触及它们) -and-的JavaScript / 1519

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM