[英]What does the Storable typeclass do in Haskell
I have been reading some documentation on Haskell's C FFI. 我一直在阅读有关Haskell的C FFI的一些文档。 And I've just encountered a typeclass called
Storable
, which I don't understand very well. 我刚刚遇到一个名为
Storable
的类型类,我不太了解它。
Are instances of this typeclass, those types are supposed to have a "pointer" to them while interfacing with the C code? 是这个类型类的实例,这些类型在与C代码接口时应该有一个“指针”吗?
Also what do the individual functions sizeOf
, alignment
, peek
, poke
do? 个别函数
sizeOf
, alignment
, peek
, poke
做什么的? It seems peek
and poke
are used to read data from or write data to a place in memory pointed to by Ptr a
. 似乎
peek
和poke
用于从Ptr a
指向的内存中读取数据或将数据写入内存中。 Is this right? 这是正确的吗?
But I don't know what sizeOf
and alignment
mean at all. 但我不知道
sizeOf
和alignment
含义是什么。 Can someone give examples to clarify their use? 有人可举例说明其用途吗?
Haskell stores values in memory in a way that is very incompatible to C. As a result, it is not possible to call a C function from haskell and pass to it haskell values directly. Haskell以与C非常不兼容的方式将值存储在内存中。因此,无法从haskell调用C函数并直接传递给它haskell值。 Instead, you have to create a copy of the value, but not an exact copy, but rather in a format that is understood by C. That's what
Storable
does. 相反,你必须创建一个值的副本,但不是一个精确的副本,而是一个C语言理解的格式。这就是
Storable
所做的。 So it essentially provides way to serialize haskell values to a C friendly format (eg think C structs). 因此它实质上提供了将haskell值序列化为C友好格式的方法(例如,想想C结构)。 It also supports the opposite operation, it can deserialize values.
它还支持相反的操作,它可以反序列化值。 This is useful when a C function is called from haskell and returns a complex (ie non primitive) value.
当从haskell调用C函数并返回复杂(即非原始)值时,这很有用。
The serialization/deserialization happens with the help of poke
/ peek
. 序列化/反序列化在
poke
/ peek
的帮助下发生。 sizeOf
returns the byte size of the C representation of the value. sizeOf
返回值的C表示的字节大小。 Note that this mechanism only works for values that have a C representation of fixed size (eg structs). 请注意,此机制仅适用于具有固定大小的C表示的值(例如,结构)。 It does not support things like C strings, they are treated differently .
它不支持像C字符串这样的东西,它们的处理方式不同 。 As for
alignment
, it used to ensure that memory allocations done in the haskell land satisfy the platform's alignment requirements. 至于
alignment
,它用于确保在haskell域中完成的内存分配满足平台的对齐要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.