[Haskell-cafe] Need help with very simple C++ FFI call

Thiago Padilha tpadilha84 at gmail.com
Tue Nov 19 14:59:07 UTC 2013


Hi

I'm trying write a ffi binding to the v8 javascript engine (C++
library). Theres one already at https://github.com/sol/v8 but I want
to do it again as an exercise to improve by haskell skills.

I chose this library be because it will force me to deal with impure
functions using monads. Since its not a trivial library, it will also
improve my knowledge of writing FFI bindings and cabal packages in
case I want to wrap more C++ libraries in the future.

My first step is to port the 'hello world' example in v8 embedders
guide(https://developers.google.com/v8/get_started) as a haskell
binding. So I have downloaded/compiled v8 and created the following
directory structure:

src/V8.hs
cbits/haskell-v8.cpp
# v8 libraries
deps/lib/libv8_base.a
deps/lib/libv8_snapshot.a
# v8 headers
deps/include/

Here's the contents of the haskell-v8.cpp file:
http://pastebin.com/RfYCCxFQ (basically a copy of the v8 embedders
example function, except that it returns a char pointer).

and here's the haskell module: http://pastebin.com/fnXVbEeU

I compiled a shared library exposing the c "hello" function with the
following command:

    $ g++ \
      -shared -o libhaskellv8.so \
      -I./deps/include \
      -L./deps/lib \
      ./cbits/haskell-v8.cpp \
      -lv8_base \
      -lv8_snapshot \
      -lpthread \
      -lrt

And loaded into ghci with the following:

    $ ghci -L. -lhaskellv8 src/V8.hs

The problem is that I get a segmentation fault when I call the 'hello'
function from ghci. To ensure the library was compiled correctly, I
successfully called it from python:

    $ python -c \
      'from ctypes import CDLL, c_char_p; lv8=CDLL("libhaskellv8.so");
lv8.hello.restype = c_char_p; print lv8.hello()'
    Hello, World!

I have selectively uncommented lines from the c++ file, and the
segmentation faults starts happening when I uncomment line 14
(HandleScope handle_scope(isolate)).

What am I missing here?


More information about the Haskell-Cafe mailing list