[Haskell-cafe] FFI and a struct containing a string and allocating memory space

Patrick Chilton chpatrick at gmail.com
Tue Aug 8 18:03:16 UTC 2017


You could make your own `withEventInfo :: EventInfo -> (Ptr CEventInfo ->
IO a) -> IO a` that calls withCString internally, and gives the passed
function a pointer that is valid for the execution of the function. You
could also use inline-c <http://hackage.haskell.org/package/inline-c> and
create a struct EventInfo when you need it, and then you know that your
bindings are typesafe, which you don't get with Storable etc.

On Tue, Aug 8, 2017 at 7:45 PM, Brian Sammon <
haskell-cafe at brisammon.fastmail.fm> wrote:

> If I have a struct like
> struct EventInfo {
>         char * event_name;
>         int year;
>         int month;
>         int date;
> }
>
> and an associated haskell datatype that I want to marshall into it, it
> seems to me that I can't take advantage of the speed advantages of alloca
> (and its friends like "with")
>
> The only safe way I've thought of to do this is to do this is to have the
> poke function for EventInfo (the associated haskell type) call malloc (or
> newCAString or something) and then poking the string into the newly
> allocated space.
> I realized after a few successful runs of using withCString in the poke
> function for EventInfo, that I don't think that this (calling withCString
> from the poke function) was a safe approach, and I'm thinking it was just
> dumb luck that this worked at all.
>
> Thoughts?  Am I on the right track?  Am I missing any better approaches?
>
> (I'm using Haskell 8.0.1 and a Storable instance for EventInfo, BTW)
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20170808/9b8561f7/attachment.html>


More information about the Haskell-Cafe mailing list