4

I am experimenting in OCaml to see how I can read/write a numerical array to/from a memory mapped file.

I think I'll need to use Bigarray but not sure how to write down a Bigarray array to a memory mapped file, and then read it back?

I cannot seem to find an example anywhere. I have checked the source code of Jane St. core but to no avail.

Robin Green
  • 32,079
  • 16
  • 104
  • 187

2 Answers2

5

Since it seems like you're interested in using core:

Here's map_file from their docs (https://ocaml.janestreet.com/ocaml-core/109.58.00/doc/core/#Bigstring)

val map_file : shared:bool -> Unix.file_descr -> int -> t

map_file shared fd n memory-maps n characters of the data associated with descriptor fd to a bigstring. Iff shared is true, all changes to the bigstring will be reflected in the file.

You should accept the answer Jonathan creates however.

rgrinberg
  • 9,638
  • 7
  • 27
  • 44
4

I'm making this an answer (I was originally afraid that I missed your point). The OCaml library provides a mechanism for this by default, namely, the map_file function from the Bigarray.Genarray module. It does precisely what you want and amounts to mmap'ing the file under Unix. I'm unsure about the Windows specifics.

This has the advantage of being well-supported and well-tested, as well as not requiring you to import JaneSt's Core into your project if you didn't need it already.

Jonathan Protzenko
  • 1,709
  • 8
  • 13
  • On a side note, is it in generally safe to mix stdlib with core code? – user2991422 Jan 07 '14 at 17:41
  • As long as you don't use async it should be safe. A lot of core's modules are wrappers around the corresponding stdlib modules. Check out the `Caml` module in core which wraps the whole stdlib in case you need to use it. – rgrinberg Jan 07 '14 at 18:35