Swift調用C、C++、Object-C,swift調用cobject-c

來源:互聯網
上載者:User

Swift調用C、C++、Object-C,swift調用cobject-c

1.Swift調用C語言
a,首先在項目中添加 CFile 檔案命名為CHello,同時產生橋樑檔案。

  

 

b,建立之後的項目結構如所示:

 

b,在CHello.h檔案中編寫介面方法,在CHello.c編寫實現方法,最後在SwiftCallC-Bridging-Header.h檔案中引入CHello.h

CHello.h檔案

#ifndef __SwiftCallC__CHello__#define __SwiftCallC__CHello__#include <stdio.h>void sayHello();#endif /* defined(__SwiftCallC__CHello__) */

CHello.c檔案

#include "CHello.h"void sayHello(){    printf("hello\n");}

SwiftCallC-Bridging-Header.h檔案

#import "CHello.h"

 

2.Swift調用OC語言
a,同理先在項目下添加object-c檔案命名為OCHello。這裡因為已經建立過檔案橋樑,這裡就不需要了。

 

b,在OCHello.h檔案中編寫介面方法,在OCHello.c編寫實現方法,最後在SwiftCallC-Bridging-Header.h檔案中引入OCHello.h標頭檔

OCHello.h檔案

#import <Foundation/Foundation.h>@interface OCHello : NSObject//方法沒有小括弧,真不適應- -!-(void) sayHello;@end

OCHello.m檔案

#import "OCHello.h"@implementation OCHello-(void)sayHello{    NSLog(@"hello");}@end

SwiftCallC-Bridging-Header.h檔案

#import "CHello.h"#import "OCHello.h"

 

c,最後在Swift代碼中調用Object-C即可以了~

import UIKitclass ViewController: UIViewController {    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        var oc = OCHello()        oc.sayHello()    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}


3.Swift調用C++語言
調用c++代碼只要將原來的OCHello.m檔案改為OCHello.mm,然後就可以在該檔案中引用iostream標頭檔....^^瞬間有c++的feel了!
最後稍微修改下實現的方法就可以了。

#import "OCHello.h"#include "iostream"using namespace std;@implementation OCHello-(void)sayHello{    cout<<"Hello"<<endl;}@end

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.