2015-11-05 22 views
0

有关如何从Swift和Objective-C调用C++的一些很好的答案。例如his answer to "Can I have Swift, Objective-C, C and C++ files in the same Xcode project?" SwiftArchitect展示了如何从Swift中调用C,C++,Objective-C,Objective-C++和Swift。使用另一个C++类作为参数调用Objective-C(++)的C++方法

但是我可以在例子中找到的C++方法的签名非常简单。我想调用一些将其他C++类作为输入和输出参数的C++方法。让我举一个虚拟的例子。这里有两个C++类。

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

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

如果我想从斯威夫特称CPPClassB::doSomethingAmazingWithTwoClassAObjects我怎么在这两个CPPClassA情况下掠过我的Objective-C++包装我CPPClassB类?

回答

-1

最简单的方法是创建ObjC包装。

//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; 

最难的方法是使用C包装。最难的,因为你需要手动执行内存管理。

相关问题