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.

    ”。


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

  • 相关阅读:
    如何使用SAP Intelligent Robotic Process Automation自动操作Excel
    OpenSAML 使用引导 IV: 安全特性
    Spring Cloud Zuul 网关使用与 OAuth2.0 认证授权服务
    微服务架构集大成者—Spring Cloud (转载)
    Spring Cloud Eureka 服务注册列表显示 IP 配置问题
    使用 Notification API 开启浏览器桌面提醒
    SignalR 中使用 MessagePack 序列化提高 WebSocket 通信性能
    配置 Nginx 的目录浏览功能
    关于 Nginx 配置 WebSocket 400 问题
    Migrate from ASP.NET Core 2.0 to 2.1
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4946683.html
Copyright © 2011-2022 走看看