[ocaml-ctypes] How to memcpy?

Jeremy Yallop yallop at gmail.com
Tue Jul 26 23:26:50 BST 2016


Dear Andre,

On 26 July 2016 at 18:24, Andre Nathan <andre at digirati.com.br> wrote:
> Say I have a C struct that looks like this:
>
>   struct thing {
>     void *buffer;
>     unsigned long length;
>   }
>
> This struct is used to pass values of multiple types to a function. For
> example, given
>
>   struct thing *t = malloc(...);
>   unsigned long len;
>
> you do something like
>
>   int x = 42;
>   len = sizeof(int);
>   t->length = len;
>   t->buffer = malloc(len);
>   memcpy(t->buffer, &x, len);
>
> or
>
>   char *s = "foo";
>   len = strlen(s);
>   t->length = len;
>   t->buffer = malloc(len);
>   memcpy(t->buffer, s, len);
>
> In OCaml I'm representing the struct as
>
>   module Thing = struct
>     type t
>     type t = thing structure
>     let t : t typ = structure "thing"
>     let buffer = field t "buffer" (ptr void)
>     let length = field t "length" ulong
>   end
>
> What I couldn't figure out was how do do the equivalent of the memcpy()
> step using Ctypes. I've found Stubs.memcpy but it doesn't seem to be
> exported.

In many cases you'll be able to avoid the call to 'memcpy' by using
'allocate' to create an initialized object, like this:

   let p = allocate int 42 in
   setf v buffer (coerce (ptr int) (ptr void) p)

But if you encounter a situation where you really need something like
'memcpy' then you may find the following little library useful:

   https://github.com/yallop/ocaml-memcpy

The library provides several flavours of memcpy, with and without
bounds checking, and to and from various kinds of objects including
OCaml bytes buffers, bigarrays, and arbitrary memory addressed by
ctypes pointers.

For completeness, I should mention that there are tricks to do the
equivalent of memcpy using just ctypes, without additional libraries,
by coercing pointers to arrays of char of appropriately sizes, but I
recommend the library approach as a better starting point.

Kind regards,

Jeremy.


More information about the Ctypes mailing list