0

There are some great answers on SO showing how to call C++ from Swift and Objective-C. For example in his answer to "Can I have Swift, Objective-C, C and C++ files in the same Xcode project?" SwiftArchitect shows how to call C, C++, Objective-C, Objective-C++, and Swift from Swift.

But the signatures of the C++ methods I can find in the examples are fairly simple. I want to call some C++ methods that take other C++ classes as input and output parameters. Let me show a dummy example. Here are two C++ classes.

class CPPClassA
{
public:
    int myState;
    int doSomethingAmazingWithTwoInts(int firstInt, int secondInt);
};

class CPPClassB
{
public:
    int doSomethingAmazingWithTwoClassAObjects(CPPClassA &firstObject, CPPClassA *secondObject);
};

If I want to call CPPClassB::doSomethingAmazingWithTwoClassAObjects from Swift how do I pass in the two CPPClassA instances in my Objective-C++ wrapper for my CPPClassB class?

Community
  • 1
  • 1
dumbledad
  • 16,305
  • 23
  • 120
  • 273

1 Answers1

-1

The easiest way is to create ObjC wrappers.

//ObjCClassA.h
@interface ObjCClassA

@property (nonatomic, assign) int myState;

- (int) doSomethingAmazingWithFirstInt:(int) firstInt secondInt:(int) secondInt;

@end

//ObjCClassA.mm
@interface ObjCClassA()
{
  CPPClassA val;
}
@end

@implementation

- (int) myState
{
    return val.myState;
}

- (void) setMyState:(int) myState
{
    val.myState = myState;
}

- (int) doSomethingAmazingWithFirstInt:(int) firstInt secondInt:(int) secondInt
{
    return val.doSomethingAmazingWithTwoInts(firstInt, secondInt);
}

@end

//ObjCClassB.h
@class ObjCClassA;

@interface ObjCClassB

- (int) doSomethingAmazingWithFisrtA:(ObjCClassA*) firstA secondA:(ObjCClassB*) secondB;

@end;

The hardest way is to use C wrappers. The hardest because you will need perform memory management manually.

Cy-4AH
  • 4,370
  • 2
  • 15
  • 22