【问题标题】:Calling a C++ method from Objective-C(++) with another C++ class as a parameter使用另一个 C++ 类作为参数从 Objective-C(++) 调用 C++ 方法
【发布时间】:2015-11-05 16:59:58
【问题描述】:

关于 SO 有一些很好的答案,展示了如何从 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++ 方法的签名相当简单。我想调用一些将其他 C++ 类作为输入和输出参数的 C++ 方法。让我展示一个虚拟的例子。这里有两个 C++ 类。

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

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

如果我想从 Swift 调用 CPPClassB::doSomethingAmazingWithTwoClassAObjects,如何在我的 CPPClassB 类的 Objective-C++ 包装器中传入两个 CPPClassA 实例?

【问题讨论】:

    标签: objective-c swift2 objective-c++


    【解决方案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 包装器。最难的,因为您需要手动执行内存管理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多