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.

    ”。


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

  • 相关阅读:
    SQLServer 2008 还原数据库备份版本不兼容的问题
    全排列函数
    n & 1
    最长公共子序列(LCS)最长递增子序列(LIS)
    unity3DGI
    多继承的缺点
    JSON文件导入Unity3d中是空的的问题
    丑数
    整数中1出现的次数
    检测鼠标是否在UI上unity
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4946683.html
Copyright © 2011-2022 走看看