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;
}
相关推荐
测试员周周44 分钟前
【Appium 系列】第14节-断言与验证 — Validator 的设计
android·人工智能·python·功能测试·ios·单元测试·appium
2501_916008895 小时前
Mac 上生成 AppStoreInfo.plist 文件,App Store 上架
android·macos·ios·小程序·uni-app·iphone·webview
人月神话-Lee7 小时前
【图像处理】高斯模糊——最优雅的模糊算法
图像处理·人工智能·算法·ios·ai编程·swift
@大迁世界7 小时前
iPhone 18e,可能不再“低一档”
ios·iphone
Daniel_Coder8 小时前
iOS Widget 开发-20:从旧版 API 迁移到 iOS 17+ 现代 Widget
ios·swift·widget·widgetcenter
Daniel_Coder8 小时前
iOS Widget 开发-19:Widget 调试与单元测试
ios·单元测试·swift·widget·widgetcenter
我是谁的程序员1 天前
Mac 上生成 AppStoreInfo.plist 文件,App Store 上架
后端·ios
sweet丶1 天前
微信Matrix 卡顿监控原理梳理与图解
ios
2501_916007471 天前
iOS开发中抓取HTTPS请求的完整解决方法与步骤详解
android·网络协议·ios·小程序·https·uni-app·iphone