Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

iphone - Adding C++ Object to Objective-C Class

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.

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

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();
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

struct Opaque {
    myCppFile cppobject;
};

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...