Search code examples
cswiftobjective-cinteropheader-files

Using multiple Objective-C header files in Swift project


I would like to use the AAPLRendererUtils and AAPLMathUtilities files from the following Apple sample code in a Swift project.

I have created a bridging header where I have imported "APPLMathUtilities.h" and it works just fine. However, when I try to import "AAPLRendererUtils.h" I run into issues.

AAPLRendererUtils.h is a header-only file and does not follow the usual Objective-C @interface and @implementation pattern.

AAPLRendererUtils.h also imports APPLMathUtilities.h so maybe this dependency is an issue?

#import "AAPLMathUtilities.h"

//----------------------------------------------------------------------------------------

struct Camera
{
    vector_float3 position;
    vector_float3 target;
    float rotation;
    float aspectRatio;      // width/height
    float fovVert_Half;     // half of vertical field of view, in radians
    float distanceNear;
    float distanceFar;

    matrix_float4x4 GetViewMatrix () const
    {
        return matrix_look_at_left_hand(position, target, (vector_float3){0,1,0});
    }

    matrix_float4x4 GetProjectionMatrix_LH () const
    {
        return matrix_perspective_left_hand (
            fovVert_Half * 2.f,
            aspectRatio,
            distanceNear,
            distanceFar);
    }
};

Interestingly, if I comment out the function declarations the code runs but if I leave them in I get the following error:

field 'GetViewMatrix' declared as a function

Since you cannot have functions in structs in C am I correct in thinking that Xcode is interpreting this file as a C file?


Solution

  • This is not a C header, it is a C++ header. The files that this gets included in, in the sample document, all have the ".mm" extension which is Objective-C++. C++ does allow structs to have methods (it's basically a class where all the members are public, IIRC). I know a couple of years ago, Swift was not very good at working with C++ files. I don't know if that's changed. You could probably separate the methods from the struct to make a C file and a header if you are diligent enough.