Re: Passing `string option' values between OCaml and C

From: Damien Doligez (
Date: Tue Sep 01 1998 - 15:43:06 MET DST

Date: Tue, 1 Sep 1998 15:43:06 +0200
From: Damien Doligez <>
Message-Id: <>
Subject: Re: Passing `string option' values between OCaml and C

>From: Christian Lindig <>

>weak_set() in byterun/weak.c tests for value el != 1 to recognize the
>Some case:

>win_create_process() in otherlibs/win32unix/createprocess.c on the
>other hand tests optional value env != Val_int(0) to do this:

Well, it is the case that Val_int(0) is equal to 1, but you should use
Val_int(0) for this purpose.

WARNING: the following information is subject to change and is not
guaranteed to work for any version of O'Caml different from 1.07
and 2.00.

This is how concrete datatypes are encoded in O'Caml.

The constant constructors have the same representation as O'Caml
integers: the first constant constructor is 0, the second one 1, etc.

The constructors with arguments are represented by memory blocks,
which include a tag in their header. The first non-constant
constructor's tag is 0, the second one 1, etc.

For example, let's consider the following declaration.

type foo =
  | AAA
  | BBB of int
  | CCC
  | DDD of string * string
  | EEE of (int -> int)
  | FFF

In this case, AAA, CCC, FFF are numbered from 0 to 2, and BBB, DDD,
EEE are again numbered from 0 to 2.

So if we have in Caml

x = AAA
y = BBB 345
z = CCC
t = DDD ("foo", "bar")
u = EEE (fun x -> x)
v = FFF

then in C,

x = Val_int(0)

Tag_val (y) = 0
Wosize_val (y) = 1
Field (y, 0) = Val_int (345)

z = Val_int(1)

Tag_val (t) = 1
Wosize_val (t) = 2
String_val (Field (t, 0)) is a zero-terminated string that contains "foo"
String_val (Field (t, 1)) is a zero-terminated string that contains "bar"

Tag_val (u) = 2
Wosize_val (u) = 1
Field (u, 0) is the closure of "fun x -> x", and could be passed as
first argument to one of the callback functions.

v = Val_int(2)


-- Damien

This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:15 MET