[ocaml-ctypes] Help with strings

Jeremy Yallop yallop at gmail.com
Wed Dec 27 13:20:59 GMT 2017

On 26 December 2017 at 23:45, john skaller <skaller at internode.on.net> wrote:
>> On 27 Dec. 2017, at 10:04, Jeremy Yallop <yallop at gmail.com> wrote:
> Hi! Sorry for the email mixuo, i’m subscribed twice now,
> once at sourceforge and once at internode.
> I have another question: what’s the best way to bind an “enum”?
> If the codes are sequential is there a builtin way to map the enum
> into an Ocaml variant?

Ctypes provides two functions for this:

   'constant' retrieves the value of a compile-time constant
(enumeration constant, #define value, etc.)

   'enum' builds a 'typ' value from a mapping between constants and OCaml values

Besides the documentation there are examples in various packages, such
as the OCaml yaml bindings:


ctypes_of_clang also provides an alternative method of bindings enums
(see the README):


> Right, thanks! That’s a definite spec, perhaps please you could add those
> comments to the documentation?

Good idea!  I'll get to that soon

> I may have some more questions, hope you don’t mind.
> Perhaps the answers will be useful to others starting out.
> BTW: some of the code appears in  several places.
> Why is that?
> (Ctypes vs Ctypes_types.TYPE)

Ctypes_type.TYPE is an abstract interface to type descriptions.  The
Ctypes module gives a default implementation of the interface.  The
interface is also used elsewhere, though; in particular, it's used for
describing C types whose layout is retrieved from C:


For example, you can bind a struct using the 'structure' and 'field'
values in the TYPE interface:

   let s = structure "s"
   let x  = field s "x" int

If you use the implementations of 'structure' and 'field in the Ctypes
module then the struct layout is computed using an implementation that
computes offsets using the alignment information for each type.  But
if you use the implementations of 'structure' and 'field' from the
Cstubs module then the layout information is retrieved by generating C
code that's run through a C compiler.  The interface (i.e. TYPE) is
the same in both cases, but it's useful to have different
implementations of that interface.

> Ok, so that’s a pointer to the live Ocaml string, and we’re relying
> on the string not being modified or moved during the C call.


> Current rules say Ocaml strings are immutable, use bytes instead.
> However, if several threads are running, normally Ocaml is using
> a global lock to serialise them. However the lock is normally
> released when calling C code. That would not be safe in this
> case, using ocaml_string, so presumably in this case the lock
> is not released. Is that correct?

Yes, that's correct.  Ctypes supports releasing the lock (via the
~release_runtime_lock argument in Foreign.foreign, or via the
concurrency policy in Cstubs), but the lock isn't released by default.

Kind regards,


More information about the Ctypes mailing list