介绍
- 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++ 代码。
#include <stdio.h>
#include <string>
struct Person {
std::string name;
int age;
};
std::vector<Person> allPerson();
#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 = createPerson("zhangsan", 20);
Person person2 = createPerson("lisi", 21);
Person person3 = createPerson("wangwu", 22);
people.push_back(person1);
people.push_back(person2);
people.push_back(person3);
return people;
}
- 在 Bridging Header 中引入 C++ 的头文件,即
#import "Person.hpp"
。
- Swift 代码。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
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 代码。
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("好好学习")
}
}
#include <iostream>
#include <Project-Swift.h>
#include <string>
using namespace Project;
int main(int argc, const char * argv[]) {
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;
}