跨语言调用

一、Objective-C

OC调用Swift:

创建桥接文件

使用@objcMembers修饰的swift类可以被OC使用

复制代码
@objcMembers class SwiftExample: NSObject {
    
    @objc func OC_Call_Swift() {
        print("oc call swift")
    }
    
    @objc static func OC_Call_Swift_static() {
        print("oc call swift static")
    }
    
    @objc class func OC_Call_Swift_class() {
        print("oc call swift class")
    }
    
}

OC部分

复制代码
#import "OCExample.h"
#import "Runner-Swift.h"

@implementation OCExample

- (void)OC_Call_Swift {
    SwiftExample *swiftExample = [[SwiftExample alloc] init];
    [swiftExample OC_Call_Swift];
    [SwiftExample OC_Call_Swift_static];
    [SwiftExample OC_Call_Swift_class];
}


@end
OC调用C和C++:

不需要桥接,可以直接调用

复制代码
#ifndef CExample_h
#define CExample_h

#include <stdio.h>

void OC_Call_C(void);

#endif /* CExample_h */

#include "CExample.h"

void OC_Call_C(void) {
    printf("oc call c");
}

#ifndef C_Example_hpp
#define C_Example_hpp

#include <stdio.h>

void OC_Call_C_(void);

#endif /* C_Example_hpp */

#include "C#Example.hpp"

void OC_Call_C_(void) {
    printf("oc call c#");
}

#import "OCExample.h"
#import "CExample.h"
#import "C#Example.hpp"

@implementation OCExample

- (void)OC_Call_C {
    OC_Call_C();
}

- (void)OC_Call_C_ {
    OC_Call_C_();
}

@end

二、Swift

Swift调用OC
复制代码
@interface OCExample : NSObject

+ (void)Swift_Call_OC_class;
- (void)Swift_Call_OC;

@end

#import "OCExample.h"

@implementation OCExample

+ (void)Swift_Call_OC_class {
    NSLog(@"swift call oc class");
}

- (void)Swift_Call_OC {
    NSLog(@"swift call oc");
}


@end

桥接文件中导入

复制代码
#import "OCExample.h"

在Swift代码中

复制代码
import Foundation

class SwiftExample {
    
    func Swift_Call_OC() {
        OCExample.swift_Call_OC_class();
        OCExample().swift_Call_OC();
    }
    
}
Swift调用C和C++

Swift不能直接调用C++代码,可以直接调用C代码,首先在桥接文件中导入

复制代码
#include "CExample.h"

#ifndef CExample_h
#define CExample_h

#include <stdio.h>

void Swift_Call_C(void);

#endif

#include "CExample.h"

void Swift_Call_C(void) {
    printf("swift call c");
}

class SwiftExample {
    
    func S_Swift_Call_C() {
        Swift_Call_C()
    }
    
}

如果使用C和C++去调用是将Swift函数使用闭包接收,然后在桥接文件中extern,然后就可以在C和C++中调用;

若要使用C和C++去调用需要在.mm文件中使用对应的方法包装,不能够直接调用。

注:本文不考虑有使用第三方库的方法,所以未包含与JS、Dart等互相调用的情况,后续会持续更新。

相关推荐
美狐美颜SDK开放平台42 分钟前
Android与iOS直播APP美颜有什么区别?视频美颜SDK开发详解
android·ios·音视频·视频美颜sdk
All for pursuit.1 小时前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
头发够用的程序员1 小时前
TensorRT 自定义算子插件实战(一):从零手写 customScaledTanh
c++·人工智能·pytorch·python·深度学习·边缘计算·jetson
哭泣方源炼蛊1 小时前
正则表达式c++内容汇集
数据库·c++·mysql·正则表达式
别动我齐刘海1 小时前
简历技术栈全面复习——UDP / TCP / CAN / ZMQ / Protobuf 通信工程
网络·c++·python·tcp/ip·机器学习·udp·github
All for pursuit.3 小时前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode
大侠归来3 小时前
C语言与C++在基础语法上的区别
java·c语言·c++
看看我呀看看我3 小时前
基于Qt的虚拟键盘
c++·qt·qt5·qt6.3
cu1434 小时前
细谈GM8229的具体功能与其应用
c语言·c++·人工智能·单片机
qq_406981035 小时前
c++构造函数初始化列表
c++