• Swift与C++如何相互调用?
  • 发布于 2个月前
  • 306 热度
    0 评论
介绍
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++ 代码。
/// hpp 堆代码 duidaima.com
#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 代码。
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 代码。
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++ 代码
#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;
}


用户评论