现在的位置: 首页 > 综合 > 正文

Objective-C调用C++代码

2013年05月11日 ⁄ 综合 ⁄ 共 1475字 ⁄ 字号 评论关闭

我想在XCode上调用C++的代码,我这这里小结一下我的方法,Hello类只是为Objective-C调用C++做的一个封装

但是我感觉这样太不方便了,如果C++的代码很多的时候,这样做就很不好,期待有人给出好的解决方案,文章最后有这个Demo的源代码
参考文章:http://blog.csdn.net/zhouhuiah/article/details/6426158

写讲解一下这个Demo的内容
1,新建一个项目,我选的是“Single View Application”,名字顺便
2,新建一个Objective-C class文件,取名为Hello
3,在项目中会出现两个文件,Hello.h和Hello.m文件,将Hello.m文件的后缀名改为.mm,即Hello.mm
4,在Hello.h文件内添加C++类,Hello.h文件内容如下所示:

#import <Foundation/Foundation.h>

@interface Hello : NSObject{
    class NewHello{
    private:int greeting_text;
    public:
        NewHello(){
            greeting_text=5;
        }
        void say_hello(){
            printf("Greeting_Text = %d",greeting_text);
        }
    };   
    NewHello *hello;
}
-(void)sayHellooooo;
@end

5,在Hello.mm文件中实现sayHellooooo方法,在这个方法中调用C++类

#import "Hello.h"
@implementation Hello
-(void)sayHellooooo{
    hello = new NewHello();
    hello->say_hello();
}
@end

6,最关键的地方,在需要调用C++类的地方,使用@class Hello,而不是#import 或者#include

#import <UIKit/UIKit.h>
//#include "Hello.h"
@class Hello;

@interface ViewController : UIViewController{
}
-(void)aaaa;
@end

7,实现调用C++类中的方法

#import "ViewController.h"

@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
        NSLog(@"dddddddd");
    Hello *aa = [[Hello alloc]init];
    [aa sayHellooooo];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
-(void)aaaa{}
@end

8,源代码:Objective-C调用C++ 博客园规定文件名不能有加号

抱歉!评论已关闭.