0

您将如何在 Zig 中等效地声明以下结构?

static struct lws_protocols protocols[] = {
    { "http", lws_callback_http_dummy, 0, 0 },
    LWS_PLUGIN_PROTOCOL_MINIMAL,
    { NULL, NULL, 0, 0 } /* terminator */
};

查看LWS_PLUGIN_PROTOCOL_MINIMAL,它在标题中定义为:

#define LWS_PLUGIN_PROTOCOL_MINIMAL \
    {  \
        "lws-minimal-proxy", \
        callback_minimal, \
        sizeof(struct per_session_data__minimal), \
        128, \
        0, NULL, 0 \
    }

struct lws_protocols {
    const char *name;
    lws_callback_function *callback;
    size_t per_session_data_size;
    size_t rx_buffer_size;
    unsigned int id;
    void *user;
    size_t tx_packet_size;
};
4

1 回答 1

0

我曾经zig translate-c -l libwebsockets minimal-ws-server.c > foo.zig从原始 C 源代码生成 zig 源文件。

然后我查看了 foo.zig 文件并提取了以下内容:

pub const struct_lws_protocols = extern struct {
    name: [*c]const u8,
    callback: ?lws.lws_callback_function,
    per_session_data_size: usize,
    rx_buffer_size: usize,
    id: c_uint,
    user: ?*c_void,
    tx_packet_size: usize,
};

pub var protocols: [0]struct_lws_protocols = [0]struct_lws_protocols{
    struct_lws_protocols{
        .name = "http",
        .callback = lws.lws_callback_http_dummy,
        .per_session_data_size = @bitCast(usize, @as(c_long, @as(c_int, 0))),
        .rx_buffer_size = @bitCast(usize, @as(c_long, @as(c_int, 0))),
        .id = 0,
        .user = null,
        .tx_packet_size = 0,
    },
};

然后我发现使用 zig C 标头导入:

const lws = @cImport(@cInclude("libwebsockets.h"));

我可以通过在名称前加上lws.eg lws.lws_callback_http_dummy(如上所用)来引用标题提供的结构(或其他定义),而不是在我的 zig 源中复制这些定义

于 2021-09-10T07:46:29.773 回答