views:

262

answers:

1

I'm considering the use of a combination between OCaml and C code in a new application. It seems that calling C code from Ocaml is simple:

    external name : type = C-function-name

However, it seems also that in the other way around (calling OCaml from C) is more complicated:

  static void
  call_ocaml_void (const char * name)
  {   CAMLparam0 () ;
      CAMLlocal1 (ostr) ;

      ostr = caml_copy_string (name);

      value * func = caml_named_value ("ocaml_puts") ;

      if (func == NULL)
          puts ("caml_named_value failed!") ;
      else
          caml_callback (*func, ostr) ;

      CAMLreturn0 ;
  } /* call_ocaml_void */

(Example from this page)

And especially, it involves copying.

Could anyone tell me if it is possible to allow access to a data structure from both languages? So the functions could pass only pointers to the structure, but both languages can read it anyway.

The objective is to do all the operations with OCaml, and then pass the data to the C environment in an efficient way.

Thanks!

+3  A: 

Firstly you can pass any C malloced value to ocaml as an abstract type. Their are severall problem with this :

  • You cannot manipulate an abstract value from ocaml without using external function defined in C
  • The garbage collector won't free them, and you might have memory leak (or to use some external function to explictly free it, but you lose part of the usefullness of ocaml)

You can also use custom block containing a pointer to anything. This is also an bastract value (as in the previous case) but you can add some code to be called when the custom block is GCed and that will take care of freeing the C object.

Then for array of integer/char/float you have the biggaray library "A pointer p to an already-allocated C or Fortran array can be wrapped and returned to Caml as a big array using the alloc_bigarray or alloc_bigarray_dims functions. " see the manual

Rémi
Perfect. That link is just what I needed. Thanks lot!
alvatar
You definitly want bigarrays. But remi, the garbage collector WILL free the abstract types, why do you think you have the custom operations struct in C and call to register them with the GC?
nlucaroni
malloc alloc memory outside the caml Heap, and caml do not GC thing outside its heap. So if your abstract value is just a C pointer to malloced memory, caml won't free it. Custom block are GCed, but not pure malloced C pointer.
Rémi