Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Converting C arrays to Ocaml arrays
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2006-04-10 (20:42)
From: Chris Campbell <cyberdanx@g...>
Subject: Converting C arrays to Ocaml arrays

I'm trying to patch lablgl to return an array of texture ids using
glGenTextures, however am a little unsure how to go about the
conversion from C array to Ocaml array.  In this case we have an array
of GLuints allocated by calloc and we wish to create an ocaml array
containing these items.  This seems simple, create an ocaml array and
copy the values.  However, in the ffi the routine caml_alloc_array
takes an array of pointers to things (terminated by NULL) and a
function that takes a pointer to a thing and returns a ocaml value.

Is the correct way then to alloc another array, then fill it with the
pointers in the original array then call caml_alloc_array?  That seems
a bit redundant, although I think I might understand why ocaml ffi
might ask for this format.  Is there a macro to help with this, or a
better way?

This is what I reckon it would look like...

CAMLprim value ml_glGenTextures(value num)

  GLuint numTextures = Int32_val(num);

  GLuint *ids = (GLunit *)calloc(numTextures, sizeof(GLuint));
  glGenTextures(numTextures, ids);

  GLuint **id_ptrs = (GLuint **)calloc (numTextures+1, sizeof(GLunit *));
  id_ptrs[numTextures] = NULL;

  for (i = 0; i < numTextures; i++)
     id_ptrs[i] = &ids[i];

  ml_tex_ids = caml_alloc_array
(&wrapper_around_copy_int32_which_takes_ptr, id_ptrs);


Am I on the right lines?

Chris Campbell