Writing a C++ Wrapper around Objective-C

后端 未结 4 1893
臣服心动
臣服心动 2020-12-30 08:58

I want to call and work with Objective-C classes from within a C++ project on OS X. It is time to start moving towards all Objective-C, but we need to do this over some time

4条回答
  •  不思量自难忘°
    2020-12-30 09:05

    Objective-C++ is a superset of C++, just as Objective-C is a superset of C. It is supported by both the gcc and clang compilers on OS X and allows you to instantiate and call Objective-C objects & methods from within C++. As long as you hide the Objective-C header imports and types within the implementation of a C++ module, it won't infect any of your "pure" C++ code.

    .mm is the default extension for Objective-C++. Xcode will automatically do the right thing.

    So, for example, the following C++ class returns the seconds since Jan 1., 1970:

    //MyClass.h
    
    class MyClass
    {
      public:
        double secondsSince1970();
    };
    
    //MyClass.mm
    
    #include "MyClass.h"
    #import 
    
    double MyClass::secondsSince1970()
    {
      return [[NSDate date] timeIntervalSince1970];
    }
    
    //Client.cpp
    
    ...
    MyClass c;
    double seconds = c.secondsSince1970();
    

    You will quickly find that Objective-C++ is even slower to compile than C++, but as you can see above, it's relatively easy to isolate its usage to a small number of bridge classes.

提交回复
热议问题