iosobjective-ccswiftc-preprocessor

Accessing C macros in Swift


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.


Solution

  • 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 :)