Injecting Haskell into C

I have a C function whose behaviour is customized by user-supplied function (think of libc qsort). Typically these user-supplied functions are written in C, but I'd like to use FFI to write them in Haskell. Precisely, I'd like to write high-order function which will generate these functions (e.g. mkCompare :: ... -> (Ptr a -> Ptr a -> Int) for feeding the result to qsort). As I understand, there are two ways to do that. Either Haskell code is called from C, or C code is called for Haskell. So my questions are: 1. Are they both possible? 2. If yes, which is better performance-wise? (C function is performance-critical). If generated function is called many times, how big an overhead is going to be? -- Roman I. Cheplyaka :: http://ro-che.info/ kzm: My program contains a bug. How ungrateful, after all I've done for it.

Hello Roman, Wednesday, September 24, 2008, 2:04:38 PM, you wrote:
As I understand, there are two ways to do that. Either Haskell code is called from C, or C code is called for Haskell. So my questions are: 1. Are they both possible?
yes. "foreign export" exports Haskell functions to C world, foreign import does opposite
2. If yes, which is better performance-wise? (C function is performance-critical). If generated function is called many times, how big an overhead is going to be?
foreign import *unsafe* -fvia-C together with -O2 may improve speed of C function calls -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com

As I understand, there are two ways to do that. Either Haskell code is called from C, or C code is called for Haskell. So my questions are: 1. Are they both possible?
Yep.
2. If yes, which is better performance-wise? (C function is performance-critical). If generated function is called many times, how big an overhead is going to be?
I'm also interested in an answer to this, since I have a program that does both, quite a bit. Of course the real answer is to try to profile it, but I'm also interested in the theory of what's going on in both directions (I'm using safe imports of course, since there are callbacks). I have a bit of a performance problem with the C->haskell part, but that may also be all the marshalling the haskell side has to do (both via the with / alloca approach, and malloc in haskell and free() in C), and I'd like to know a bit more before I go wild trying to cache data in C that comes from haskell.
participants (3)
-
Bulat Ziganshin
-
Evan Laforge
-
Roman Cheplyaka