Version française
Home     About     Download     Resources     Contact us    
Browse thread
How to wrap around C++?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Michael Ekstrand <michael+ocaml@e...>
Subject: Re: How to wrap around C++?
On 02/07/2010 08:13 PM, Luca de Alfaro wrote:
> Essentially, the C++ object implements access to a file via some
> compression, etc, mechanism.  In C++, one creates the object, calls
> write and read methods, calls the method for closing the file, and
> deletes the object. 
> 
> How can I wrap around such an object in Ocaml?  Is it possible?  Any
> advice? 

It is possible.  One way would be to use Swig.  The other is to write
the wrappers yourself, providing OCaml external functions for each of
the methods you want to call.  If it's just a few methods, it isn't too
difficult.  The documentation on interfacing with OCaml from C (in the
manual) is quite helpful with several examples, albeit all for C.  For
C++, there are just a few additional things to think about (that I know of):

* Make sure no C++ exceptions leak to OCaml.
* Wrap your OCaml includes in 'extern "C" { ... }"
* Export all your stub functions with C linkage (extern "C")
* Compiling is tricky, since the OCaml compiler driver doesn't know what
to do with C++.  The Swig documentation[1] has a workaround for this,
useful even if you don't use Swig.

You can use OCaml's custom object support to manage the class instnaces.
 Your custom block will store a pointer to the object.  The finalizer
will then need to take care of deleting the object (or decreasing its
reference count, or whatever is appropriate).

The basic thing you'll do is to create an ML file defining an abstract
type for your object, external functions for your wrapper stubs (which
need to be plain C functions taking and returning OCaml values), and
then whatever higher-level convenience functions (or classes, if you
want to re-wrap the C++ code in an OCaml object-oriented interface) you
want to expose for actually using the module.

- Michael