caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] Non-toplevel C functions using OCaml values
@ 2012-01-09  2:35 Harrison, John R
  2012-01-09  7:33 ` Gerd Stolpmann
  0 siblings, 1 reply; 3+ messages in thread
From: Harrison, John R @ 2012-01-09  2:35 UTC (permalink / raw)
  To: caml-list; +Cc: Harrison, John R

I have a question about interfacing C and OCaml functions that I
didn't see an answer to in the manual, though maybe I just didn't look
carefully enough. I think I pretty well understand how to set up a C
function that is designed to be called directly by OCaml. But what
about a function that I want to use internally as a utility, callable
by other C functions that are themselves called by OCaml?

For example, if I want to implement a function designed to be called
directly by OCaml and basically equivalent to the OCaml definition

  let cons h t = h::t;;

then I think (correct me if I'm wrong) that I do the following:

  CAMLprim value caml_cons(value h,value t)
  { CAMLparam2(h,t);
    CAMLlocal1(newblock);
    newblock = caml_alloc(2,0);
    Store_field(newblock,0,h);
    Store_field(newblock,1,t);
    CAMLreturn(newblock);
  }

But what if I want to set up a utility that I'm only going to call
from other C functions, and which involves a mixture of standard C
types and OCaml values among its arguments or local variables, and/or
allocates OCaml values? For example, suppose I want to implement the
special case of the above "cons" for int lists where the first
argument is a C int (which I assume to be in range for an OCaml
int). I might guess that I would do something like this:

  value int_cons(int h,value t)
  { CAMLparam1(t);
    CAMLlocal1(newblock);
    newblock = caml_alloc(2,0);
    Store_field(newblock,0,Val_int(h));
    Store_field(newblock,1,t);
    CAMLreturn(newblock);
  }

and then just call it like any other C function. However, I can
imagine several other plausible alternatives, e.g. that I should skip
some or all of the special CAMLsomething functions, or that I should
just forget the idea and use OCaml values throughout, calling it as if
it were any other OCaml function. Can someone enlighten me?

John.



^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2012-01-09  9:23 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2012-01-09  2:35 [Caml-list] Non-toplevel C functions using OCaml values Harrison, John R
2012-01-09  7:33 ` Gerd Stolpmann
2012-01-09  9:23   ` ygrek

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).