zoukankan      html  css  js  c++  java
  • 在Xcode中使用C++与Objective-C混编

    有时候,出于性能或可移植性的考虑,需要在iOS项目中使用到C++。

    假设我们用C++写了下面的People类:

    1. //  
    2. //  People.h  
    3. //  MixedWithCppDemo  
    4. //  
    5. //  Created by Jason Lee on 12-8-18.  
    6. //  Copyright (c) 2012年 Jason Lee. All rights reserved.  
    7. //  
    8.   
    9. #ifndef __MixedWithCppDemo__People__  
    10. #define __MixedWithCppDemo__People__  
    11.   
    12. #include <iostream>  
    13.   
    14. class People  
    15. {  
    16. public:  
    17.     void say(const char *words);  
    18. };  
    19.   
    20. #endif /* defined(__MixedWithCppDemo__People__) */  

    1. //  
    2. //  People.cpp  
    3. //  MixedWithCppDemo  
    4. //  
    5. //  Created by Jason Lee on 12-8-18.  
    6. //  Copyright (c) 2012年 Jason Lee. All rights reserved.  
    7. //  
    8.   
    9. #include "People.h"  
    10.   
    11. void People::say(const char *words)  
    12. {  
    13.     std::cout << words << std::endl;  
    14. }  

    然后,我们用Objective-C封装一下,这时候文件后缀需要为.mm,以告诉编译器这是和C++混编的代码:
    1. //  
    2. //  PeopleWrapper.h  
    3. //  MixedWithCppDemo  
    4. //  
    5. //  Created by Jason Lee on 12-8-18.  
    6. //  Copyright (c) 2012年 Jason Lee. All rights reserved.  
    7. //  
    8.   
    9. #import <Foundation/Foundation.h>  
    10. #include "People.h"  
    11.   
    12. @interface PeopleWrapper : NSObject  
    13. {  
    14.     People *people;  
    15. }  
    16.   
    17. - (void)say:(NSString *)words;  
    18.   
    19. @end  

    1. //  
    2. //  PeopleWrapper.mm  
    3. //  MixedWithCppDemo  
    4. //  
    5. //  Created by Jason Lee on 12-8-18.  
    6. //  Copyright (c) 2012年 Jason Lee. All rights reserved.  
    7. //  
    8.   
    9. #import "PeopleWrapper.h"  
    10.   
    11. @implementation PeopleWrapper  
    12.   
    13. - (void)say:(NSString *)words  
    14. {  
    15.     people->say([words UTF8String]);  
    16. }  
    17.   
    18. @end  

    最后,我们需要在ViewController.m文件中使用PeopleWrapper:
    1. PeopleWrapper *people = [[PeopleWrapper alloc] init];  
    2. [people say:@"Hello, Cpp. "];  
    3. [people release], people = nil;  

    结果发现编译通不过,提示“iostream file not found”之类的错误。

    这是由于ViewController.m实际上也用到了C++代码,同样需要改后缀名为.mm。

    修改后缀名后编译通过,可以看到输出“

    Hello, Cpp.

    ”。


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    优酷网的架构学习笔记
    同网关劫持与不同网关劫持实例
    .flv和.swf格式文件flash播放器代码
    让IE6显示透明PNG背景图片
    新手买车的九大原则
    服务器不支持FLV视频播放的原因
    功能强大易用的Web视频播放器——Flowplayer(使用方法及演示)
    一个不错的媒体网页播放器(国外的)
    网页表格中单元格线条及边框的设置
    20多个漂亮的使用jQuery交互的网站设计欣赏
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4946683.html
Copyright © 2011-2022 走看看