Haskell FFI - 如何处理接受或返回结构而不是指向结构的指针的C函数?

时间:2021-11-09 17:02:53

Of course the answer is to somehow pass/take a contiguous block of memory, so the question is more about how to do that. For now I could still avoid the issue by writing wrapper functions on the C side, but that's not much of a permament solution.

当然答案是以某种方式传递/采取连续的内存块,所以问题更多的是如何做到这一点。现在我仍然可以通过在C端编写包装函数来避免这个问题,但这并不是一个永久性的解决方案。

1 个解决方案

#1


12  

The FFI doesn't support arbitrary pass by value Haskell storable types.

FFI不支持任意传递值Haskell可存储类型。

You may only pass values of type (and some of these are pointers):

您只能传递类型的值(其中一些是指针):

Int#, Word#,
Char#,
Float#, Double#,
Addr#,
StablePtr# a, MutableByteArray#, ForeignObj#, and ByteArray#.

So, to pass a structure you must wrap the call via a C wrapper; which takes a pointer and passes its value to the C function you wish to actually call.

因此,要传递结构,必须通过C包装器包装调用;它接受一个指针并将其值传递给您希望实际调用的C函数。

A recent GHC extension allows for "primop" imports -- which bypass the FFI mechanism and support arbitrary calling conventions and passing structures via unboxed tuples. E.g.

最近的GHC扩展允许“primop”导入 - 它绕过FFI机制并支持任意调用约定并通过未装箱的元组传递结构。例如。

foreign import prim "ITCHv41_run"
  parseITCHv41# :: Addr# -> Word#
                -> (# Int#, Word#, Word#, Word#, Word#, Word# #)

You can use these to do tricky low level stuff like this.

你可以使用它们做这样棘手的低级别的东西。

#1


12  

The FFI doesn't support arbitrary pass by value Haskell storable types.

FFI不支持任意传递值Haskell可存储类型。

You may only pass values of type (and some of these are pointers):

您只能传递类型的值(其中一些是指针):

Int#, Word#,
Char#,
Float#, Double#,
Addr#,
StablePtr# a, MutableByteArray#, ForeignObj#, and ByteArray#.

So, to pass a structure you must wrap the call via a C wrapper; which takes a pointer and passes its value to the C function you wish to actually call.

因此,要传递结构,必须通过C包装器包装调用;它接受一个指针并将其值传递给您希望实际调用的C函数。

A recent GHC extension allows for "primop" imports -- which bypass the FFI mechanism and support arbitrary calling conventions and passing structures via unboxed tuples. E.g.

最近的GHC扩展允许“primop”导入 - 它绕过FFI机制并支持任意调用约定并通过未装箱的元组传递结构。例如。

foreign import prim "ITCHv41_run"
  parseITCHv41# :: Addr# -> Word#
                -> (# Int#, Word#, Word#, Word#, Word#, Word# #)

You can use these to do tricky low level stuff like this.

你可以使用它们做这样棘手的低级别的东西。