ForeignPtr question (was Re: debug with GHC FFI?)
paul@theV.net
paul@theV.net
Thu, 6 Mar 2003 12:57:23 +0800
I am using Green Card 2.05, but it seems to me that its support
for Ptr/Addr types are not up-to-date. I then use ForeignPtr
to marshall a C structure, but have some problem with pointers
which is garbage collected too early.
Here is a code sample:
------------------------ snip ------------------------
%fun destroyByteBuffer :: Addr -> IO ()
%code if (arg1) { free(arg1); }
%result ()
data ByteBufferType = ByteBufferType
type ByteBuffer = ForeignPtr ByteBufferType
marshall_byteBuffer :: ByteBuffer -> IO Addr
marshall_byteBuffer ptr = withForeignPtr ptr (\x -> return (ptrToAddr x))
unmarshall_byteBuffer :: Addr -> IO ByteBuffer
unmarshall_byteBuffer addr = newForeignPtr (addrToPtr addr) (destroyByteBuffer addr)
%fun readInt :: ByteBuffer -> IO Int
%call (byteBuffer (addr bf))
%code INT32 r, v = 0;
% r = bb_get_int((Byte_Buffer *) bf, &v);
%fail {r != _NO_ERR} {"readInt failed"}
%result (int v)
------------------------ snip ------------------------
The code would sometimes segfault in bb_get_int(..), and since
it was coded in a separate C file, I was able to trace down
the error in GDB, which hinted that, part of the C structure in
"bf" was already freed prior to the bb_get_int(..) function call.
So my guess is that "destroyByteBuffer" was invoked even when
I use "withForeignPtr" to marshall the ByteBuffer type.
What did I do wrong here? Is it a bug with Greencard or something
I am still missing when constructing a garbage collectible
ForeignPtr in FFI?
Regards,
.paul.
On Tue, Feb 25, 2003 at 09:49:00PM +0800, paul@theV.net wrote:
> I am using Green Card to make some FFI modules with GHC, but
> sometimes it segfaults in the middle of nowhere, leaving
> no sensible stack trace in gdb.
>
> I wonder what is the proper way to debug FFI modules written
> in C? Trying to add a "-g" flag doesn't seem help at all...
>
> Regards,
> .paul.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe