这是我在 Zig 0.7.0 中通过 linux-x86_64 上的 @cImport 导入 Zig 的一些 C 代码。当我直接在 Zig 中创建一个struct Point
结构时,它按预期工作,但是当我从getPoint
方法中按值返回一个时,有错误的数据(参见下面的“输出”)。我做错了什么,还是这是一个错误?
- 点.h
struct Point {
int x;
int y;
int z;
};
struct Point getPoint(void);
- 点.c
#include "point.h"
#include <stdio.h>
struct Point getPoint() {
struct Point retVal = { .x=50, .y=50, .z=50 };
return retVal;
}
- 主要的.zig
const std = @import("std");
const c = @cImport({
@cInclude("point.h");
});
pub fn main() void {
var point = c.getPoint();
var anotherPoint = c.Point{ .x = 50, .y = 50, .z = 50 };
std.debug.print("point x: {} y: {} z: {}\n", .{ point.x, point.y, point.z });
std.debug.print("anotherPoint x: {} y: {} z: {}\n", .{ anotherPoint.x, anotherPoint.y, anotherPoint.z });
}
- 输出
point x: 50 y: 50 z: -1705967616
anotherPoint x: 50 y: 50 z: 50
- 构建.zig
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
//const lib = b.addStaticLibrary("interface", "src/libinterface.a");
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("point_test", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.linkLibC();
exe.addIncludeDir("src");
exe.install();
exe.addCSourceFile("src/point.c", &[_][]const u8{
"-Wall",
"-Wextra",
"-Werror",
});
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}