Accessing C macros in Swift

好久不见. 提交于 2020-01-07 09:33:27

问题


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

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

Unable to resolve the symbol.

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.


回答1:


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

Complex macros are used in C and Objective-C but have no counterpart in 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).

For instance, given this C macro:

#define SQUARE(n) n * n

Define this C function in another header file:

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

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 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.

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.

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

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

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



来源:https://stackoverflow.com/questions/43663917/accessing-c-macros-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!