gpt4 book ai didi

在 OCaml 函数的 C 实现中创建求和类型

转载 作者:太空狗 更新时间:2023-10-29 15:35:45 24 4
gpt4 key购买 nike

假设您有一个类型声明:

type foo = Bar | Baz of int

您将如何实现 C function创建一个 Baz?假设我这样声明:

external create_baz : int -> foo = "create_baz"

然后我需要填写这个代码:

CAMLprim value create_baz(value bar) {
// what do I do here?
}

我知道这是一件相当愚蠢的事情,但这只是我正在尝试做的事情的一个例子。

最佳答案

这在 Chapter 19 of the OCaml manual 中有描述.

基本上,构造函数在两个单独的序列中按顺序编号。 Nullary 构造函数(不带值的构造函数,如 Bar)按一个序列编号,带值的构造函数(如 Baz)按第二序列编号。所以你的两个构造函数都编号为 0。

Nullary 构造函数由立即值表示(表示类似 int 的值的简单位模式)。取值的构造函数由指向 block 的指针表示, block 具有可以存储所含值的字段。

所以,基本上您的函数想要创建一个大小为 1 且标记为 0 的 block 。bar 保存在 block 的第 0 个字段(唯一的字段)中。

看起来像这样:

value create_baz(value bar) {
// Caller guarantees that bar is an int.
//
CAMLparam1(bar);
CAMLlocal1(result);
result = caml_alloc(1, 0);
Store_field(result, 0, bar);
CAMLreturn(result);
}

关于在 OCaml 函数的 C 实现中创建求和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23482995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com