Доступ к структурам, возвращаемым по значению из функций C в Zig
Вот код C, который я импортирую в Zig через @cImport. Когда я напрямую создаю
struct Point
struct в Zig работает должным образом, но когда я возвращаю единицу по значению из
getPoint
метод имеют неверные данные (см. "вывод" ниже). Я что-то не так делаю или это ошибка?
- point.h
struct Point {
int x;
int y;
int z;
};
struct Point getPoint(void);
- point.c
#include "point.h"
#include <stdio.h>
struct Point getPoint() {
struct Point retVal = { .x=50, .y=50, .z=50 };
return retVal;
}
- main.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
- build.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);
}
1 ответ
Совместимость c abi Zig в настоящее время имеет некоторые проблемы со структурами и числами с плавающей запятой.
Конкретная проблема, с которой вы столкнулись, #3211, была исправлена, и теперь ваш код будет работать.
$> zig run main.zig point.c -I.
point x: 50 y: 50 z: 50
anotherPoint x: 50 y: 50 z: 50
Тем не менее, проблемы с взаимодействием C abi все еще остаются, например: #9487 .
Пока все эти проблемы не будут устранены, их часто можно обойти, используя указатели, а не передачу по значению для аргументов и возвращаемых значений.
// workaround.h
#include "point.h"
void workaround_getPoint(struct Point* out);
// workaround.c
#include "workaround.h"
void workaround_getPoint(struct Point* out) {
*out = getPoint();
}
// .zig
const c = @cImport({
@cInclude("point.h");
@cInclude("workaround.h");
});
pub fn getPoint(): c.Point {
var res: c.Point = undefined;
c.workaround_getPoint(&res);
return res;
}
// build.zig
exe.addCSourceFile("src/workaround.c", &.{ "-Wall", "-Wextra", "-Werror" });