09-外部函数接口

Wan Yutong Lv2

作为一个Toy LanguageAlum的生态极为弱小,这限制了我们编写一些比较复杂的程序,我们可以通过FFI(Foreign Function Interface,即:外部函数接口)用其他语言为Alum编写拓展,这里最推荐的是C语言,因为Alum的数据在内存布局上与C语言几乎一致,不需要转换的开销。可以通过extern直接引入外部函数。

extern关键字

extern关键字是Alum与外部函数(不论是Alum还是其他语言)打交道的桥梁,它的语法如下:

1
extern F(PTn, ...): RT

例如,我们每次调用println函数都要$import "io.al",但其实,也可以通过

1
extern println(string): void

的方式直接定义,但还是推荐引入io.al,这样更方便也更直观。

C语言的兼容性

我们直接用示例介绍,还记得在02-Installation中安装的almk工具吧?它可以很好的帮我们处理AlumC语言的混合编译与连接问题。关于almk我们会在未来的章节讲解,下面是AlumC语言混合编程的例子:

  1. 首先在终端输入:
1
$ almk new c_compat
  1. 然后,编辑c_compat/Alumake.toml文件,像下文所示(只要build部分类似即可):
1
2
3
4
5
6
7
8
9
10
11
12
13
[package]
name = "c_compat"
version = "0.1.0"
author = ""
license = ""
language = "mixed"

[build]
linker = "alc"
cc = "cc"
alc = "alc"
cflags = "-Wall -O2 -nostdlib"
includes = ["./include"]
  1. 接着创建目录c_compat/include,并将以下代码写入helper.al文件中:
1
2
3
4
5
6
7
8
$ifndef HELPER_AL
$define HELPER_AL nil

extern c_add(int, int): int
extern c_multiply(int, int): int
extern c_calculate_factorial(int): int

$endif // HELPER_AL
  1. 并将以下代码写入src/helper.c文件中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "helper.h"

int c_add(int a, int b) {
return a + b;
}

int c_multiply(int a, int b) {
return a * b;
}

int c_calculate_factorial(int n) {
if (n < 0) {
return 0;
}

int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}

return result;
}
  1. 最后,修改src/main.al文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$import "io.al"
$import "convert.al"
$import "helper.al"

fun main(): int {
let sum: int = c_add(10, 20)
print("c_add(10, 20) = ")
println(itoa(sum))

let product: int = c_multiply(5, 6)
print("c_multiply(5, 6) = ")
println(itoa(product))

let factorial: int = c_calculate_factorial(5)
print("c_calculate_factorial(5) = ")
println(itoa(factorial))

return 0
}
  1. 在终端进入c_compat/目录后执行almk run或者almk build && ./target/c_compat便能得到输出:
1
2
3
c_add(10, 20) = 30
c_multiply(5, 6) = 30
c_calculate_factorial(5) = 120

注:示例代码来自Alum/examples/15_mixed_c_alum

  • Title: 09-外部函数接口
  • Author: Wan Yutong
  • Created at : 2026-02-28 19:49:16
  • Updated at : 2026-03-03 11:38:47
  • Link: https://cr0.dpdns.org/2026/02/28/09-FFI/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
09-外部函数接口