gpt4 book ai didi

c - swift Zeromq C 桥接 header - 找不到类型

转载 作者:行者123 更新时间:2023-11-30 17:25:27 30 4
gpt4 key购买 nike

我正在尝试使用 czmq 为 Zeromq 构建 Swift 绑定(bind)。​​

我已经在 xcode 中配置了一个桥接 header ,它似乎理解了这一点,但我仍然收到此错误:

/Users/jjl/code/swiftzmq/src/zsock.swift:47:37: error: use of undeclared type 'zsock_t'
typealias zsock_ptr = UnsafePointer<zsock_t>

在 C 中使用它,如果我这样做,我将可以使用此类型(这是我的桥接 header 的确切内容):

#include <czmq.h>

我知道它被包含在内,因为它提示头文件之一中的某些内容,直到我链接到正确的库路径为止。

我不知道从这里该去哪里。如果您能提供任何帮助,我们将不胜感激

我的项目位于https://github.com/jjl/swiftzmq

最佳答案

我明白发生了什么事。 swift 互操作层不够聪明,无法理解 czmq 作者以更好的代码为名在编译器工具链上玩的技巧,因此我们必须进行一些 C 包装以将其隐藏在 swift 面前。

简单的部分:

  • 删除 #include <czmq.h>来自桥接头的行
  • 添加一行导入您选择的另一个 header (我选择 szsocket.h 因为它是 swift zsocket 包装器)
  • 创建相应的 .c 文件和 #import <czmq.h>

较难的部分:

您需要在 header 中重新创建库使用的所有结构。就我而言 zsock_t结构体定义如下:

typedef struct zsock_t {
uint32_t tag; // Object tag for runtime detection
void *handle; // The libzmq socket handle
char *endpoint; // Last bound endpoint, if any
char *cache; // Holds last zsock_brecv strings
int type; // Socket type
size_t cache_size; // Current size of cache
} zsock_t;

我们创建一个简单的包装器,如下所示:

typedef struct szsock_t {
uint32_t tag; // Object tag for runtime detection
void *handle; // The libzmq socket handle
char *endpoint; // Last bound endpoint, if any
char *cache; // Holds last zsock_brecv strings
int type; // Socket type
size_t cache_size; // Current size of cache
} szsock_t;

您还需要重新创建这些结构中使用的任何类型定义。在这种情况下,轻易没有其他人。这些都在新的头文件 (.h) 中

然后,您需要包装库中接受这些结构之一的每个函数。我们取zsock_new以函数为例。

首先,我们需要在 header 中预先声明我们的版本,以避免任何 zsock 类型。我们只需替换所有出现的 zsockszsock (emacs 可以帮助解决这个问题):

szsock_t *szsock_new (int type, const char *filename, size_t line_nbr);

接下来我们需要在 .c 文件中创建包装函数:

szsock_t *szsock_new (int type, const char *filename, size_t line_nbr) {
return (szsock_t *) zsock_new(type, filename, line_nbr);
}

注意我们如何在 zsock_t 之间进行转换和szsock_t并使用内部 zsock 函数。这样做是安全的,因为 swift 编译器不会读取它,只有 c 编译器会读取它。

接下来,有一堆可变参数函数。这对我有用:

int szsock_bind (szsock_t *self, const char *format, ...) {
int ret;
va_list args;
va_start(args, format);
ret = zsock_bind( (zsock_t *) self, format, args);
va_end(args);
return ret;
}

祝所有阅读用 swift 包装库的人好运!

关于c - swift Zeromq C 桥接 header - 找不到类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27074730/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com