跨语言调用

一、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等互相调用的情况,后续会持续更新。

相关推荐
—Qeyser3 小时前
Flutter 颜色完全指南
android·flutter·ios
王维志4 小时前
使用C#控制台批量删除 Unity目录里的 .meta文件
unity·c#·.net
de之梦-御风4 小时前
【C#.Net】C#开发的未来前景
开发语言·c#·.net
2501_916008895 小时前
iOS 上架需要哪些准备,账号、Bundle ID、证书、描述文件、安装测试及上传
android·ios·小程序·https·uni-app·iphone·webview
de之梦-御风5 小时前
【C#.Net】C#在工业领域的具体应用场景
开发语言·c#·.net
Dream it possible!6 小时前
LeetCode 面试经典 150_二分查找_在排序数组中查找元素的第一个和最后一个位置(115_34_C++_中等)
c++·leetcode·面试
月光下的麦克7 小时前
如何查案动态库版本
linux·运维·c++
小六子成长记7 小时前
【C++】:搜索二叉树的模拟实现
数据结构·c++·算法
汉克老师7 小时前
GESP2025年9月认证C++二级真题与解析(编程题1(优美的数字))
c++·算法·整除·枚举算法·求余·拆数
wuk9987 小时前
基于C#与三菱PLC通过TCPIP实现MC协议通信示例
java·网络·c#