Hello FFI-ers, While the FFI spec. is excellent, I'd really like to see a companion document with real examples of how to use the FFI for the easy, obvious kinds of library interfacing tasks that are likely to arise in practice. Such examples would hopefully help answer things like the following rather naieve question that I have: Is there a particular "best" way to deal with C functions that take "lightweight" struct values (or pointers to such structs), such as the classic: struct point { float x, y; }; ? Should I treat this is an opaque ForeignPtr, use heap allocation everywhere, and abandon pattern matching on the Haskell side? Or should I create a data type on the Haskell side, and marshall and un-marshall this to the C side as necessary (perhaps by writing wrapper routines that take x and y as separate arguments)? Or can I use Storable in some way to do better than either of the above options? It's just not clear to me from the specification. Any help would be appreciated. Thanks, -antony -- Antony Courtney Grad. Student, Dept. of Computer Science, Yale University antony@apocalypse.org http://www.apocalypse.org/pub/u/antony
I made a start on writing an FFI howto at: http://www.reid-consulting-uk.ltd.uk/docs/ffi.html It is very rough, doesn't answer your specific question, has many typos and omissions, etc. but some of the links in the Tips and Tricks section (section 4) might help. To answer your question directly, I think it all depends on what you're doing. Sometimes the semantics of the operations make it easy. For example, if there is any notion of object identity (and it often isn't stated whether there is or not), you usually have to keep the master copy in the C world and not duplicate. If there is no notion of identity, no modification to the object, etc., it is often easiest to keep it on the Haskell side and copy over to the C side on each operation because it's easier. There may be a performance hit in doing this depending on the number of times it is copied in each direction but I don't think we have any numbers for a range of implementations (ghc numbers may be available). Without any effort at measurement, I'd say that using malloc is pretty slow (because C's malloc is pretty slow) and that ForeignPtr's are fairly low overhead but more than just copying a small object over. -- Alastair Reid alastair@reid-consulting-uk.ltd.uk Reid Consulting (UK) Limited http://www.reid-consulting-uk.ltd.uk/alastair/
participants (2)
-
Alastair Reid -
Antony Courtney