Let's say you had a type declaration:
type foo = Bar | Baz of int
How would you implement a C function to create a Baz? Let's say I declare it like this:
external create_baz : int -> foo = "create_baz"
Then I would need to fill out this code:
CAMLprim value create_baz(value bar) {
// what do I do here?
}
I understand that this is a rather silly thing to do, but it's just and example of what I'm trying to do.
This is described in Chapter 19 of the OCaml manual .
Basically, constructors are numbered in order, in two separate sequences. Nullary constructors (those taking no values, like Bar
) are numbered in one sequence, and constructors that take a value (like Baz
) are numbered in a second sequence. So both of your constructors are numbered 0.
Nullary constructors are represented by immediate values (a simple bit pattern representing a value like an int). Constructors taking values are represented by pointers to blocks, which have fields that can store the contained values.
So, basically your function wants to make a block of size 1 with tag 0. bar
is saved in the block's 0th field (the only field).
It looks something like this:
value create_baz(value bar) {
// Caller guarantees that bar is an int.
//
CAMLparam1(bar);
CAMLlocal1(result);
result = caml_alloc(1, 0);
Store_field(result, 0, bar);
CAMLreturn(result);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.