Swift 5.9 新特性—C++互操作性

介绍

  • Swift 5.9 之前 Swift 与 C++ 互操作需要借助于 Objective-C,即 Swift ↔ Objective-C ↔ C++。
  • Swift 5.9 之后 Swift 与 C++ 的类型函数有了可以直接交互的能力。
  • 重要配置:Build Settings ---> Swift Complier - Language ---> C++ and Objective-C Interoperability ---> 选择 C++/Objective-C++。

Swift调用C++

  • 创建基于 Swift 的 iOS 项目,然后新建 C++ 文件,此时需要激活并创建 Bridging Header。
  • C++ 代码。
c 复制代码
/// hpp
#include <stdio.h>
#include <string>

struct Person {
    std::string name;
    int age;
};
std::vector<Person> allPerson();

/// cpp
#include "Person.hpp"

Person createPerson(std::string name, int age) {
    Person person;
    person.name = name;
    person.age = age;
    return person;
}

std::vector<Person> allPerson() {
    std::vector<Person> people;
    Person person1 = {"zhangsan", 20};
    Person person2 = {"lisi", 21};
    Person person3 = {"wangwu", 22};
    people.push_back(person1);
    people.push_back(person2);
    people.push_back(person3);
    return people;
}
  • 在 Bridging Header 中引入 C++ 的头文件,即#import "Person.hpp"
  • Swift 代码。
swift 复制代码
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // 直接访问C++代码
        let person = Person(name: "zhaoliu", age: 23)
        for person in allPerson() {
            print(person.name, person.age)
        }
    }
}

C++调用Swift

  • 创建基于 C++ 的 Command Line Tool 项目,然后新建 Swift 文件,此时也需要激活并创建 Bridging Header。
  • Swift 代码。
swift 复制代码
import Foundation

public class Person {
    public var name: String
    public var age: Int

    public init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    public func study() {
        print("好好学习")
    }
}
  • C++ 代码。
c 复制代码
#include <iostream>
#include <Project-Swift.h>
#include <string>
using namespace Project;

int main(int argc, const char * argv[]) {
     // 直接访问Swift代码
    Person person = Person::init("zhangsan", 20);
    std::string name = person.getName();
    long age = person.getAge();
    std::cout << "Name: " << name << ", Age: " << age << std::endl;
    person.study();
    return 0;
}
相关推荐
2501_9160088914 小时前
深入解析iOS应用启动性能优化策略与实践
android·ios·性能优化·小程序·uni-app·cocoa·iphone
美狐美颜SDK开放平台15 小时前
短视频/直播双场景美颜SDK开发方案:接入、功能、架构详解
android·ios·美颜sdk·第三方美颜sdk·视频美颜sdk
库奇噜啦呼16 小时前
【iOS】内存对齐原理
macos·ios·cocoa
SameX1 天前
我做了个专注 App,把连续打卡阈值从 3/7/14 改成 2/5 之后留存明显好了
ios
pop_xiaoli1 天前
【iOS】分类、关联对象
ios·分类·数据挖掘·objective-c·cocoa
Mr -老鬼1 天前
EasyClick iOS版 CLI 与 Trae iOS版智能体
ios·自动化·ai编程·tare·ec·easyclick·易点云测
wechatbot8881 天前
企业微信 iPad 协议接口全功能开发实战
汇编·人工智能·ios·微信·企业微信·ipad
Digitally1 天前
如何将视频从 iPhone 传输到电脑
ios·电脑·iphone
大熊猫侯佩2 天前
别被系统绑架:SwiftUI List 替换背后的底层逻辑
swiftui·swift·apple