5

I am able to export simple haskell functions through FFI containing standard data types. However, I do not know how to export a function that takes data type other than standard data types.

E.g.

data SomeType a = SomeType a
data SomeOtherType b = SomeOtherType b

doSomething:: SomeType a -> SomeOtherType b

How can I export function doSomething?

The existing documents talks about very simple examples.

Jonke
  • 6,525
  • 2
  • 25
  • 40
Yogesh Sajanikar
  • 1,086
  • 7
  • 19
  • 3
    You can only export functions that work on the types that C knows about. – augustss Aug 29 '12 at 23:57
  • 3
    Related (duplicate?) question: http://stackoverflow.com/questions/4502115/interchange-structured-data-between-haskell-and-c/4504674 – John L Aug 30 '12 at 02:53

2 Answers2

2

The alternative is to lift the function to use StablePtr, and export the function with the StablePtr. Of Course as pointed out in the above answer you have use the function with instance that cane be exported.

It would be great to use something like H/Direct to plumb this code into c++ objects so that it can be accessed as object.

Yogesh Sajanikar
  • 1,086
  • 7
  • 19
  • `StablePtr` can't be dereferenced outside of Haskell. So if your goal was to share the actual data and process it in another language then this wouldn't work. That's why `StablePtr` don't have a `Storable` requirement. As for H/Direct, You can use `Hs2lib` to generate the marshalling information for you. Though I haven't maintained it in a while I don't know how it works with the newer GHCs. – Phyx Aug 31 '12 at 11:49
  • Well sometimes it is good to have opacity. Though I would love to try hs2lib and let you know, unfortunately it doesn't get installed with newer GHC (primarily because of version dependency on filepath). – Yogesh Sajanikar Oct 09 '12 at 18:02
  • Yeah, I saw that. There were a few other issues. I'll see if I can correct them this weekend. – Phyx Oct 11 '12 at 17:35
1

Short answer is, you can't.

You need to pick an instance of the function and export that.

e.g. doSomething :: SomeType Int -> SomeOtherType Int is exportable. I wrote a longer answer here that might be helpful

The reason is that the Haskell side needs to know how to marshall the structure, how much memory to allocate etc.

Community
  • 1
  • 1
Phyx
  • 2,697
  • 1
  • 20
  • 35
  • Thanks! But data types such as Data.Set might be large to be marshaled. Is there any technique to mask such data types? – Yogesh Sajanikar Aug 30 '12 at 15:31
  • Nah, The only way I know of to get the data out of Haskell is to serialize or to Marshal it. Alternatively you could also create a Set that's file based using memory mapped files. You wouldn't need to do much to read it back in from another language then. – Phyx Aug 31 '12 at 11:43