美文网首页
Swift,Objective-C,C,C++混合编程

Swift,Objective-C,C,C++混合编程

作者: 土豆吞噬者 | 来源:发表于2019-08-22 18:50 被阅读0次

    OC调用C/C++

    OC可以无缝调用C/C++,调用C++时将文件名由.m改为.mm即可。

    OC调用Swift

    OC调用Swift,OC文件中需要import "项目名-Swift.h",Swift文件中类需要继承NSObject,方法前面要加@objc,编译时Xcode会将Swift代码转为OC代码放在"项目名-Swift.h"中。

    import Foundation
    
    class MySwiftClass:NSObject {
        
        @objc func saySomething(str:String){
            print(str)
        }
    }
    
    #import "ViewController.h"
    #import "studyoc-Swift.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    - (IBAction)testButtonDidClick:(id)sender {
        MySwiftClass* swiftObj=[[MySwiftClass alloc] init];
        [swiftObj saySomethingWithStr:@"hello world"];
    }
    @end
    

    Swift调用OC

    在Swift项目中新建OC文件时可以自动创建桥接文件(项目名-Bridging-Header.h),在桥接文件中包含OC头文件即可使用OC代码,桥接文件路径可以在Build Settings中修改。

    MyOCClass.h

    #ifndef MyOCClass_h
    #define MyOCClass_h
    
    #import <Foundation/Foundation.h>
    
    @interface MyOCClass : NSObject
    
    -(void)printSize;
    
    @property(nonatomic) int size;
    
    @end
    #endif 
    

    MyOCClass.m

    #import "MyOCClass.h"
    
    @interface MyOCClass()
    @end
    
    @implementation MyOCClass
    
    - (void) printSize{
        printf("self.size=%d\n",self.size);
    }
    @end
    

    studyswift-Bridging-Header.h

    #import "MyOCClass.h"
    

    MainViewController.swift

    import UIKit
    
    class MainViewController: UIViewController {
    
        @IBOutlet weak var testButton: UIButton!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
        }
    
        
        @IBAction func button1DidClick(_ sender: Any) {
            let ocObj=MyOCClass()
            ocObj.size=200
            ocObj.printSize()
        }
        
    }
    

    Swift调用C

    Swift调用C和Swift调用OC方法完全一样。

    CTest.h

    #ifndef CTest_h
    #define CTest_h
    
    void printSomething(const char* str);
    
    #endif
    

    CTest.c

    #include <stdio.h>
    #include "CTest.h"
    
    
    void printSomething(const char* str)
    {
        printf(str);
    }
    

    studyswift-Bridging-Header.h

    #include "CTest.h"
    

    MainViewController.swift

    import UIKit
    
    class MainViewController: UIViewController {
    
        @IBOutlet weak var testButton: UIButton!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
        }
    
        
        @IBAction func button1DidClick(_ sender: Any) {
            printSomething("hello world")
        }
        
    }
    

    Swift调用C++

    Swift不能直接调用C++,但可以调用OC,OC再去调用C++。

    相关文章

      网友评论

          本文标题:Swift,Objective-C,C,C++混合编程

          本文链接:https://www.haomeiwen.com/subject/otuosctx.html