Objective-C調用C++代碼


我想在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++ 博客園規定文件名不能有加號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM