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

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++。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值