libnbd-ocaml - how to use libnbd from OCaml


 let nbd = NBD.create () in
 NBD.connect_uri nbd "nbd://localhost";
 let size = NBD.get_size nbd in
 printf "%Ld\n" size;
 NBD.close ()

Alternate syntax which ensures that close is called even if an exception is thrown:

 let size =
   NBD.with_handle (
     fun nbd ->
       NBD.connect_uri nbd "nbd://localhost";
       NBD.get_size nbd
   ) in
 printf "%Ld\n" size

To compile:

 ocamlopt -I +nbd mlnbd.cmxa -o prog

or using findlib:

 ocamlfind opt -package nbd -linkpkg -o prog


This manual page documents how to use libnbd to access Network Block Device (NBD) servers from the OCaml programming language.

The OCaml bindings work very similarly to the C bindings so you should start by reading libnbd(3).

For OCaml API documentation see NBD(3).


Create a libnbd handle of type NBD.t by calling NBD.create ().

You can either close the handle explicitly by calling NBD.close or it will be closed automatically when it is garbage collected. If you call any other method on a handle which you have explicitly closed then the API will throw an NBD.Closed exception.

NBD.with_handle can be used to make sure the handle is closed in a timely manner. See the example in the "SYNOPSIS" above.


Libnbd errors are turned automatically into exceptions of type:

 NBD.Error (str, Unix.error option)

The first exception parameter is a string which is the printable error message. The second is the OCaml Unix.error code, if available (see nbd_get_errno(3)).

Callbacks with "int ref" error parameter

Some callbacks take an error parameter of type int ref, corresponding to the int *error passed to those callbacks in C. See also: "Callbacks with "int *error" parameter" in libnbd(3)

If an error occurs during the callback you can update the int in the reference, setting it to a C-compatible errno. To convert an OCaml Unix.error into a C-compatible errno call NBD.errno_of_unix_error.


This directory contains examples written in OCaml:


libnbd(3), NBD(3).


Richard W.M. Jones


Copyright Red Hat


This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA