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
allocating memory for c-structures
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2006-12-26 (18:35)
From: Richard Jones <rich@a...>
Subject: Re: [Caml-list] allocating memory for c-structures
On Tue, Dec 26, 2006 at 07:15:35PM +0100, micha wrote:
> Normaly I allocate memory for c-structures with malloc or with "new" for 
> c++ objects. Some time ago a read about a library which places external 
> structures in strings of the interfacing languages (it was a scheme lib 
> I think). So instead of using malloc or new I would allocate an 
> ocaml-string and put the c-structure there. So it will be free by the gc.
> That seems o.k. for me, any comments? I'm missing something?

That seems like it'll work for "opaque" C objects, but it's a bit of a
hack.  The immediate issues I can think are:

(a) Pointers in the C code which point at the object will not be
"counted" by the GC, and so the object may be collected while there
are still C pointers around.  This is easily avoided in OCaml, but
read chapter 18 of the manual carefully.

(b) By storing the object as a string you're telling the GC not to
examine the inside of the object, eg. looking for pointers inside to
other objects.  Fine, if you know what you're doing, but OCaml already
has a number of established ways to do this - eg. using Abstract or
Custom blocks - and these standard ways are not just standard, but
offer additional features too.  Alternatively you may consider a
non-abstract block and deliberately allow the GC to look inside.  C
and OCaml structures are not actually too different.

Actually, while I was writing the above, it struck me that perhaps
you're talking about some sort of marshalling system?  OCaml supports
its own marshalling format, and a rich variety of other external forms
of marshalling.


Richard Jones, CTO Merjis Ltd.
Merjis - web marketing and technology -
Internet Marketing and AdWords courses - - NEW!
Merjis blog - - NEW!