[Haskell-cafe] Calling a C function that returns a struct by value
Matthew Steele
mdsteele at alum.mit.edu
Wed May 25 22:19:50 CEST 2011
From Haskell, I want to call a C function that returns a struct by
value (rather than, say, returning a pointer). For example:
typedef struct { double x; double y; } point_t;
point_t polar(double theta);
I can create a Haskell type Point and make it an instance of Storable
easily enough:
data Point = Point CDouble CDouble
instance Storable Point where -- insert obvious code here
And now I want to do something like this:
foreign import ccall unsafe polar :: CDouble -> IO Point
...but that doesn't appear to be legal (at least in GHC 6.12). Is
there any way to import this C function into Haskell _without_ having
any additional wrapper C code? I mean, I suppose I could write
something like:
// C:
void polar_wrapper(double theta, point_t* output) {
*output = polar(theta);
}
-- Haskell:
foreign import ccall unsafe polar_wrapper :: CDouble -> Ptr Point -
> IO ()
polar :: CDouble -> IO Point
polar theta = do -- insert obvious code here
...but that's a lot of extra boilerplate if I have many such functions
to wrap, and it seems like GHC should be able to do that sort of thing
for me. P-:
Cheers,
-Matt
More information about the Haskell-Cafe
mailing list