[ocaml-ctypes] Defines, and Structs with platform-specific fields

Jeremy Yallop yallop at gmail.com
Mon Oct 20 09:25:00 BST 2014

On 18 October 2014 12:49, Trevor Smith <trevorsummerssmith at gmail.com> wrote:
> Your suggestion makes sense. If I were to do that -- any suggestions of how
> to deal with freeing that memory? Ideally, without adding a lifecycle "free"
> call to the user library. My thoughts would be to store the cstruct
> reference (malloced by C) in a ref in OCaml, then attach a finalizer to the
> OCaml ref that would call the corresponding C free.

That approach should work, I think.

Another possibility to allocate the struct using Ctypes.allocate or
Ctypes.allocate_n -- e.g. by allocating an array of char and coercing
the result:

    val allocate : ?finalise:('a ptr -> unit) -> 'a typ -> 'a -> 'a ptr

    val allocate_n : ?finalise:('a ptr -> unit) -> 'a typ -> count:int -> 'a ptr

    val coerce : 'a typ -> 'b typ -> 'a -> 'b

The memory allocated by 'allocate' will be freed automatically when
there are no OCaml references to the object.  The optional 'finalise'
argument is for associating additional cleanup functions, not for
freeing the memory.  You may be able to use it to call uv_loop_close,
for example.

> Aside: I wonder if ctypes could be extended to deal with this cross platform
> issue fully in ctypes-land? Have others thought about this?

Yes: we're planning to add support for obtaining struct layout from C,
much as generated functions stubs are checked against C declarations:


The feature is taking a little while longer than anticipated to land,

> Also: are the maintainers open to documentation contributions? I noticed
> that a lot of these questions on the FAQ are currently unanswered. I would
> be happy to throw a couple commits with documentation suggestions for the
> problems that I am running into.

Yes: documentation contributions are very welcome.

More information about the Ctypes mailing list