在Swift中访问C宏 [英] Accessing C macros in Swift

查看:155
本文介绍了在Swift中访问C宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个第三方C库,可导出带有参数的预处理器宏

I have a third party C library exporting lots of preprocessor macros with arguments.

问题是当我尝试在Swift中访问它们时它会失败,并显示以下信息:

Problem is when I try to access them in Swift it fails with:


无法解析该符号。

Unable to resolve the symbol.

通过Swift访问第三方库导出的C宏的方法是什么?

What is the way to access such C macros, exported by third party libraries, in Swift?

我不想通过直接调用以 __ 开头的名称的函数来解决问题,并使我的代码看起来丑陋,也不想编辑/修改第三方库。

I do not want to workaround by directly calling functions with name starting with __ and make my code look ugly nor do want to edit/hack third party library.

推荐答案

没有简单的答案。前述 Apple文档非常清楚地说明了这一点:

There is no easy answer. The aforementioned Apple documentation states this pretty clearly:


复杂的宏用于C和Objective-C,但没有

Complex macros are used in C and Objective-C but have no counterpart in Swift.

但是,如果您确实需要调用这些(丑陋的)C宏,则可以定义C99 inline 周围的函数(然后从您的Swift代码中调用这些函数)。

But, if you really need to call those (ugly!) C macros, you could define C99 inline functions around them (and call those instead from your Swift code).

例如,给定此C宏:

#define SQUARE(n) n * n

在另一个头文件中定义此C函数:

Define this C function in another header file:

inline double square(double n) {
    return SQUARE(n);
}

我知道的 exact 并非同一件事—请注意,我必须使用 double 数字类型;那些疯狂的文字/符号操作也不起作用;等等-但可能会让您半途而废:)

Not the exact same thing I'm aware — note that I had to commit to the double number type; those crazy text/symbol manipulation won't work either; etc — but might get you halfway there :)

Pure Swift替代。当然,您也可以使用 protocols generics 等来模拟其中一些C语言宏,从而将 all 所有C宏手动转换为Swift惯用函数。 C宏魔术。

Pure Swift alternative. Of course, you could also convert all those C macros to idiomatic Swift functions by hand, using protocols, generics, etc to emulate some of the C macros magic.

如果我走这条路,那我就是个偏执狂的工程师! —我将原始转换后的标头的MD5与当前文件版本进行比较,如果两个哈希都不匹配,则Xcode构建将失败。

If I went this route — being the paranoid engineer that I'm! — I would compare the MD5 of the original, converted header against the current file version and fail the Xcode build if both hashes don't match.

这很容易做到通过 pre-action 构建脚本,例如:

This could easily be done by a pre-action build script such as:

test EXPECTED_HASH != $(md5 HEADER_PATH) && exit 1

如果此构建步骤失败,那么现在是时候检查您的(手动)转换后的Swift代码了,然后更新 EXPECTED_HASH :)

If this build step fails, then it's time to review your (manually) converted Swift code and update the EXPECTED_HASH afterwards :)

这篇关于在Swift中访问C宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆