Consolidating String Constants Among C++, Objective-C++ and Swift

I’m back to writing a synth audio unit. The Apple Example AudioUnit(s) Code is good, but one thing that bothers me about it is how many bare string constants there are.

I put up a GitHub project that shows what I did.

The basic idea is this:

  • Create an Objective C++ header. This file is divided into 3 logical sections:
    • #defines for each string (e.g. #define ATTACK_TYPE_STR “attackType”)
    • extern declaration for each const char array (e.g. extern const char attackTypeCTag[];)
    • inside #ifdef __OBJC__ protection, the interface declaration for a class that groups related strings together (e.g. @interface ADTags : NSObject { …). This includes declarations of string properties. This class is never intended to be instantiated. The strings are all class properties.
  • Create on Object-C++ .mm file. This file is divided into 3 sections as well:
    • The definition of the C-style string arrays.
    • The definition of static NSStrings, one for each C string.
    • The implementation of the grouping class. There is one class ‘get’ method for each string.

The Swift bridging header needs to #import the Objective C++ header. Surprisingly, I found that nothing barfs because of the C preprocessing macros in this file.

This might be overkill, but there is everything one might want — a macro of the actual text, a C array of the text, and an object that provides Objective-C (and therefore Swift) access to these strings. The raw text appears only once (in the macros in the hpp file).

Leave a Reply

Your email address will not be published. Required fields are marked *