【问题标题】:Using a C++ method as an ObjC selector?使用 C++ 方法作为 ObjC 选择器?
【发布时间】:2010-05-24 09:54:59
【问题描述】:

我想在我的混合 C++/ObjC 项目中进行某种转发。

我的逻辑是 C++,我想提供一个属于 C++ 对象实例的方法作为 objC 的选择器。有没有办法做到这一点?

主要的问题是,有没有将 C++ 方法伪装成选择器 :),将其提供给 ObjC 并让它被回调?

提前致谢, 阳极。

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    不可能为 C++ 方法获取选择器,因为它们不是由 Objective-C 运行时管理的。但是,您可以:

    • 使用普通的 C++ 函数指针来实现回调
    • 或者:创建一个 Objective-C 方法(最好是类方法)来包装对 C++ 方法的调用。然后,您可以为此功能使用选择器。

    【讨论】:

      【解决方案2】:

      您可以将 C++ 对象包装在 Objective-C 代理对象中:

      @interface MyObjCClass: NSObject {
        MyCPPClass *thing;
      }
      -(int)foo;
      @end
      
      @implementation MyObjCClass {
      
        -(id)init {
          if (self = [super init]) {
            thing = new MyCPPClass();
          }
          return self;
        }
      
        -(void)dealloc {
          delete thing; // It's been a long time since I last did C++; I may have the incorrect syntax here
          [super init];
        }
      
        -(int)foo {
          return thing->foo();
        }
      }
      @end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多