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@e...>
Subject: Re: How to wrap around C++?
On 02/08/2010 10:03 AM, Luca de Alfaro wrote:
> Thank you very much!  I follow the general lines, but...
> 
>     * Make sure no C++ exceptions leak to OCaml.
> 
> This will be next to impossible: the C++ code I need to wrap is huge,
> and I have no idea of what possible exceptions can be generated.  I will
> have to try to see if there is a generic exception catcher. 

There is.

try {
   some code
} catch (...) {
   caml_failwith("foo: exception thrown");
}

with appropriate considerations for freeing memory, etc.

>     * Wrap your OCaml includes in 'extern "C" { ... }"
> 
> 
> Here, I am not sure what you mean.  You mean, 
> 
> extern "C" {
> #include <caml/mlvalues.h>
> ...
> }
> 

Exactly.

>     * Export all your stub functions with C linkage (extern "C")
> 
> Ok, evidently, I need to learn this extern "C" construct.

Yes, if you're interfacing between C and C++, you do need to know it.
In this context, it is applied as a modifier to the function definition
(like static).  The big thing it does is turn off the name mangling used
by the C++ compiler to implement overloading, type safety, etc.

>     * 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.
> 
> 
> Why would the Ocaml compiler driver need to know what to do with C++? 
> The C++ I need to link to is rather huge, and I will need to compile it
> with its own build setup. 
> Once that is built, I need to compile the stubs, the Ocaml, and link the
> three together (Ocaml, stubs, and C++), in native mode, but  why would
> the Ocaml compiler need to deal with C++?

You will have 3 pieces: the C++ library, the OCaml interface, and the
stubs gluing them together.  Stubs must be C-compatible, so they can be
called from OCaml.  But they also need to be able to call into C++,
hence they must be written in C++.  Therefore, your stub code must be
written in C++, exporting a C-compatible interface (via extern "C").
Generally, you use the OCaml compiler driver to compile stubs rather
than gcc directly, but OCaml doesn't know how to call g++.

- Michael