本文介绍了在Objective-C周围编写一个C ++包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在OS X中的C ++项目中调用和使用Objective-C类。现在是开始向所有Objective-C开始的时候了,但是我们需要在一段时间内完成。



如何完成这个?

解决方案

是C ++的超集,就像Objective-C是C的超集一样。它由gcc和clang编译器支持OS X,并允许您实例化和调用Objective-C对象&方法从C ++。只要你在C ++模块的实现中隐藏Objective-C头的导入和类型,它不会感染任何你的纯C ++代码。



.mm 是Objective-C ++的默认扩展名。因此,例如,下面的C ++类返回自1970年1月1日以来的秒数:




  // MyClass.h 

class MyClass
{
public:
double secondsSince1970 ;
};

//MyClass.mm

#includeMyClass.h
#import< Foundation / Foundation.h>

double MyClass :: secondsSince1970()
{
return [[NSDate date] timeIntervalSince1970];
}

//Client.cpp

...
MyClass c;
double seconds = c.secondsSince1970();

你会很快发现Objective-C ++比C ++编译慢得多,上面,它相对容易将其使用隔离到少数桥类。


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.

How does one go about accomplishing this? Can anyone shed some light and provide an example?

解决方案

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 <Foundation/Foundation.h>

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.

这篇关于在Objective-C周围编写一个C ++包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:41