将Objective-C类添加到C ++对象 [英] Adding C++ Object to Objective-C Class

查看:209
本文介绍了将Objective-C类添加到C ++对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想混合C ++和Objective-C,我已经做了大部分的方式,但希望有一个单一的接口类之间的Objective-C和C ++代码。因此,我想在ViewController接口中有一个持久的C ++对象。

I'm trying to mix C++ and Objective-C, I've made it most of the way but would like to have a single interface class between the Objective-C and C++ code. Therefore I would like to have a persistent C++ object in the ViewController interface.

这样做失败了禁止myCppFile的声明没有类型:

This fails by forbidding the declaration of 'myCppFile' with no type:

#import <UIKit/UIKit.h>
#import "GLView.h"
#import "myCppFile.h"

@interface GLViewController : UIViewController <GLViewDelegate>
{
    myCppFile cppobject;
}

@end

.mm实现文件(它不工作,因为我想cppobject持续之间调用)

However this works just fine in the .mm implementation file (It doesn't work because I want cppobject to persist between calls)

#import "myCppFile.h"
@implementation GLViewController
- (void)drawView:(UIView *)theView
{
    myCppFile cppobject;
    cppobject.draw();
}


推荐答案

=http://en.wikipedia.org/wiki/Opaque_pointer> opaque指针,并且只包括实现你的Objective-C类的文件中的C ++头文件。这样你不强制其他包含标题的文件使用Objective-C ++:

You should use opaque pointers and only include C++ headers in the file that implements your Objective-C class. That way you don't force other files that include the header to use Objective-C++:

// header:
#import <UIKit/UIKit.h>
#import "GLView.h"

struct Opaque;

@interface GLViewController : UIViewController <GLViewDelegate>
{
    struct Opaque* opaque;
}
// ...
@end




b
$ b


// source file:
#import "myCppFile.h"

struct Opaque {
    myCppFile cppobject;
};

@implementation GLViewController
// ... create opaque member on initialization

- (void)foo
{
    opaque->cppobject.doSomething();
}
@end

这篇关于将Objective-C类添加到C ++对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆