Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
How to pass C pointers to Caml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2010-03-01 (23:01)
From: Florent Monnier <monnier.florent@g...>
Subject: Re: [Caml-list] How to pass C pointers to Caml
Le lundi 1 mars 2010 14:24:45, Goswin von Brederlow a écrit :
> Florent Monnier <> writes:
> > Le lundi 1 mars 2010 04:55:00, Jianzhou Zhao a écrit :
> >> I have been calling OCaml code from C in my project.
> >> The C code has some pointers to C structures.
> >> I got 'seg fault' when calling the OCaml function receiving
> >> C structure pointers.
> >>
> >> 18.7 at
> >> gives the examples that pass int into OCaml. These examples work for me.
> >> But, Does OCaml support to pass C structure pointers to OCaml?
> >
> > Yes it does. Just cast your pointer to the type value.
> >
> > In this tutorial there is an example "Pointers to C structures":
> >
> >
> > the pointer to a C struct is wrapped on the ocaml side by an abstract
> > type called "t" here, and it is provided back to C with print_t /
> > dump_ptr.
> The problem with this trivial approach is that ocaml can store the
> pointer somewhere. When the C pointer is freeed then ocaml has a
> dangling pointer. Worse, if the GC allocates a new heap then the pointer
> might suddenly point into the heap and then BOOM.

A lot of bindings wrap C pointer, it is known to be a technic that does work.
Dangerous that's true, be if you are very careful, it works.
What you can do is set the pointer to NULL when the struct is freed, and then 
each function that uses this struct pointer can first check if the pointer is 
NULL or not before to use it, and if it's NULL raise an exception.

> It is better to put the pointer into an abstract or custom block.

You can do this too.