• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

在Xcode中使用C++与Objective-C混编

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

有时候,出于性能或可移植性的考虑,需要在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.\n"];  
  3. [people release], people = nil;  

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

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

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

Hello, Cpp.

”。


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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
谈谈Objective-C链式语法的实现发布时间:2022-07-12
下一篇:
[EffectiveObjective-C读书笔记]第1章几条基本写法(2~5条)发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap