[ocaml-ctypes] structures

john skaller skaller at internode.on.net
Wed Jan 3 07:42:41 GMT 2018


Just thought, as a novice, I’d report on my latest attempt to use Ctypes
to bind some C structs. The bottom line: it took me hours, i found it confusing,
and wished there were  an example in the tutorial which included

(a) the C code
(b) Ocaml interface (mli file)
(c) Ocaml implementation (ml file)

The source of my confusion is the amount of “types” involved!
Ocaml uses separate namespaces for types and values, and this
is used in Ctypes. Supposedly to make things simpler, for me it
made things much harder.

Its not just the types but the operators do this too, for example
“ptr” has two meanings, depending on context.

When you’re binding you have a C type to think about,
possibly with two names, a structure tag name as well as
a typedef name.

Then, you have an Ocaml type representing the C type.
Then, you have an Ocaml value encoding the binding information,
which is a “type” representation. And that representation itself
has an Ocaml type, the type of the encoding value, which is distinct
from the type of the Ocaml value used to represent the C value.

Throw in the use of the same name for these things and my solution
was to just try all the possible combinations until something compiled.

This finally seems to work:


(* C HEADER FILE ****)
struct __ccc_t;
typedef struct __ccc_t *ccc_t;
void ccc_destroy(ccc_t);

(* MLI FILE *********)
type __ccc_t_tag
type __ccc_t_struct = __ccc_t_tag structure
type __ccc_t_type = __ccc_t_struct typ



(* pointer alias *)
type ccc_t = __ccc_t_struct ptr
val ccc_t : ccc_t typ

val ccc_destroy: ccc_t  -> unit


(* ML FILE ********)
type __ccc_t_tag
type __ccc_t_struct = __ccc_t_tag structure
type __ccc_t_type = __ccc_t_struct typ
let __ccc_t_tag  : __ccc_t_type = structure "__ccc_t_tag"

(* pointer alias *)
type ccc_t = __ccc_t_struct ptr
let ccc_t: ccc_t typ = ptr (__ccc_t_tag)

let ccc_destroy =  foreign "ccc_destroy" (
  ccc_t @-> returning void
)


That’s a lot of code for 3 lines of C. This is real code (with the name
changed to protect the guilty).

The phrase “ccc” occurs 5 times in the C code and
27 times in the Ocaml code.

I have made a choice that the structure “tag” name used in C is the
only way to define the Ocaml struct, and where C uses a typedef
to introduce a non-tag name, Ocaml will use an alias also.
Since Ctypes  doesn’t split struct tag name space from type namespace
I have added “_tag” to the tag name.

I’m currently testing with dynamic/libffi link but I can see this isn’t going
to cut it, either performance wise or interms of getting messy stuff like
bit fields working .. so Cstubs unfortunately looks like a requirement
(as well as some hand written extra C to cope with bitfields).


—
john skaller
skaller at users.sourceforge.net
http://felix-lang.org



More information about the Ctypes mailing list