Haskell FFI-您可以从Haskell数据结构中获取C指针吗? [英] Haskell FFI - can you obtain a C Pointer from a Haskell data structure?

查看:94
本文介绍了Haskell FFI-您可以从Haskell数据结构中获取C指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多类似的C结构

typedef struct {
    unsigned int a;
    unsigned int b;
} StructA;

还有很多功能,例如

void doSomethingWith(StructA*,StructB*,StructC*);

有没有一种简单的方法可以使用Haskell FFI调用这些函数?例如,是否有类似&的行为C中的运算符? (我想没有,但是如果有的话我想知道).我必须使Haskell端的data实例可存储(这些结构没有任何构造函数).

Is there an easy way to call these functions with Haskell FFI? Like, is there something that behaves like the & operator in C? (I imagine there isn't, but if there was I'd like to know). Do I have to make the Haskell side data's instance of storeable (I don't have any constructor functions for these structs).

也:如果我必须传递一个结构而不是一个结构指针(这不是一个假设的问题,我有一些类似的功能-这不是我的代码,所以我对此无能为力),我可以传递结构的组件呢?就像我想打电话

Also: If I have to pass a struct instead of a struct pointer (not a hypothetical question, I have a few functions like that - it's not my code so I can't do anything about it), can I just pass the components of the struct instead? Like if I want to call

void function(StructA);

我可以用

foreign import ccall "function" :: CUInt -> CUInt -> IO()

?

推荐答案

要将对Haskell数据的引用传递给C,该内存在Haskell堆中分配,并且C将直接对数据进行操作,您需要:

To pass a reference to Haskell data to C, where the memory is allocated in the Haskell heap, and C will operate on the data directly, you need to:

  • ensure it has the correct shape in memory (via a Storable instance that maps A to the an identical byte structure as StructA).
  • allocate and fill pinned memory on the Haskell heap, via mallocForeignPtr

这种方法有几个后果要考虑:

There are several consequences to consider in this approach:

  • 一旦删除对ForeignPtr的所有引用,GHC就会取消分配该值-因此,您需要确保C端不会再碰到它
  • 您要让C弄乱Haskell堆上的内容,因此请确保其正确

其他选项:

  • 通过StablePtr
  • 将不透明引用传递给C
  • 在C端分配和存储,并使用终结器将其释放.
  • pass opaque references to C via a StablePtr
  • allocate and memory on the C side, and use a finalizer to free it.

这篇关于Haskell FFI-您可以从Haskell数据结构中获取C指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆