与C交互 #
一、基本用法 #
1.1 导入C头文件 #
zig
const std = @import("std");
const c = @cImport({
@cInclude("stdio.h");
});
pub fn main() void {
_ = c.printf("Hello from C!\n");
}
1.2 调用C函数 #
zig
const std = @import("std");
const c = @cImport({
@cInclude("stdlib.h");
@cInclude("string.h");
});
pub fn main() void {
const size: usize = 100;
const ptr = c.malloc(size);
defer c.free(ptr);
_ = c.memset(ptr, 0, size);
std.debug.print("Allocated {} bytes\n", .{size});
}
二、类型转换 #
2.1 C类型映射 #
zig
const std = @import("std");
const c = @cImport({
@cInclude("stdint.h");
});
pub fn main() void {
const c_int: c_int = 42;
const zig_int: i32 = c_int;
const c_size: usize = 100;
const zig_usize: usize = c_size;
std.debug.print("c_int: {}, zig_int: {}\n", .{ c_int, zig_int });
}
三、链接C库 #
3.1 构建脚本 #
zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{
.name = "myapp",
.root_source_file = b.path("src/main.zig"),
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
});
exe.linkSystemLibrary("c");
exe.linkSystemLibrary("m");
b.installArtifact(exe);
}
四、导出函数 #
4.1 导出给C调用 #
zig
const std = @import("std");
export fn add(a: i32, b: i32) i32 {
return a + b;
}
export fn greet(name: [*:0]const u8) void {
std.debug.print("Hello, {s}!\n", .{std.mem.span(name)});
}
五、总结 #
C交互要点:
| 特性 | 说明 |
|---|---|
| @cImport | 导入C头文件 |
| @cInclude | 包含头文件 |
| linkSystemLibrary | 链接C库 |
| export | 导出函数 |
下一步,让我们学习构建系统!
最后更新:2026-03-27