Haskell FFI - can you obtain a C Pointer from a Haskell data structure?

99封情书 提交于 2019-12-03 10:04:00

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:

  • GHC will de-allocate the value once you drop all references to the ForeignPtr -- so you will need to be sure that the C side won't touch it again
  • You're letting C mess with stuff on the Haskell heap, so make sure its correct

Other options:

  • pass opaque references to C via a StablePtr
  • allocate and memory on the C side, and use a finalizer to free it.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!