简体   繁体   English

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

[英]Create sum type in C implementation of OCaml function

Let's say you had a type declaration: 假设你有一个类型声明:

type foo = Bar | Baz of int

How would you implement a C function to create a Baz? 你如何实现一个C函数来创建一个Baz? Let's say I declare it like this: 比方说我这样声明:

external create_baz : int -> foo = "create_baz"

Then I would need to fill out this code: 然后我需要填写这段代码:

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

I understand that this is a rather silly thing to do, but it's just and example of what I'm trying to do. 我知道这是一件相当愚蠢的事情,但这只是我想要做的事情的一个例子。

This is described in Chapter 19 of the OCaml manual . 在OCaml手册的第19章中有所描述。

Basically, constructors are numbered in order, in two separate sequences. 基本上,构造函数按两个单独的顺序按顺序编号。 Nullary constructors (those taking no values, like Bar ) are numbered in one sequence, and constructors that take a value (like Baz ) are numbered in a second sequence. Nullary构造函数(那些没有值,如Bar )在一个序列中编号,而取值(如Baz )的构造函数在第二个序列中编号。 So both of your constructors are numbered 0. 所以你的两个构造函数都编号为0。

Nullary constructors are represented by immediate values (a simple bit pattern representing a value like an int). Nullary构造函数由立即值表示(一个简单的位模式表示像int这样的值)。 Constructors taking values are represented by pointers to blocks, which have fields that can store the contained values. 获取值的构造函数由指向块的指针表示,这些指针具有可以存储包含值的字段。

So, basically your function wants to make a block of size 1 with tag 0. bar is saved in the block's 0th field (the only field). 所以,基本上你想要的功能,使大小1与0标签块bar被保存在块的第0场(唯一的字段)。

It looks something like this: 它看起来像这样:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM