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.

    ”。


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

  • 相关阅读:
    Selenium简单测试页面加载速度的性能(Page loading performance)
    Selenium Page object Pattern usage
    Selenium如何支持测试Windows application
    UI Automation的两个成熟的框架(QTP 和Selenium)
    分享自己针对Automation做的两个成熟的框架(QTP 和Selenium)
    敏捷开发中的测试金字塔(转)
    Selenium 的基础框架类
    selenium2 run in Jenkins GUI testing not visible or browser not open but run in background浏览器后台运行不可见
    eclipse与SVN 结合(删除SVN中已经上传的问题)
    配置Jenkins的slave节点的详细步骤适合windows等其他平台
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4946683.html
Copyright © 2011-2022 走看看