Swift 调用C++代码

github地址:https://github.com/LINGLemon/LXFSwiftApp

1.创建c++文件:Person.cpp和Person.hpp

//
//  Person.cpp
//

#include "Person.hpp"
#include "PersonExtern.h"

Person::Person(){
    age = 12;
    sex = true;
    name = "LINGLemon";
}

Person::Person(const char* name , const int age , const bool sex){
    this->age = age;
    this->sex = sex;
    
    long len = strlen(name);
    char * cpname = new char[len + 1];
    strcpy(cpname, name);
    this->name = cpname;
}

Person::~Person(){
    cout << "Person destruct\n";
}

void Person::introduceMySelf(){
    cout << "Hello, I am " << name << ", my age is " << age << " years old. ";
    if (sex) {
        cout << "I am a boy.\n";
    } else {
        cout << "I am a girl.\n";
    }
}

#pragma mark - 实现PersonExtern.h中的函数

void* person_init() {
    return new Person();
}

void person_introduceMySelf(void* person) {
    Person *p = (Person*)person;
    p->introduceMySelf();
}
//
//  Person.hpp
//

#ifndef Person_hpp
#define Person_hpp

#include <stdio.h>
#include <iostream>

using namespace std;

class Person {
    
public:
    string name;
    int age;
    bool sex;
    
public:
    //默认构造函数,相当于init
    Person();
    //带参数的构造函数,相当于带参数的init
    Person(const char* name , const int age , const bool sex);
    //析构函数,用来释放资源,相当于deinit
    ~Person();
   
    //自我介绍
    void introduceMySelf();
    
};

#endif /* Person_hpp */

2、创建PersonExtern.h文件(Swift能直接使用C代码但不能直接使用C++代码,所以在写好C++代码后,要使用C代码对C++代码进行封装,把C代码的函数声明暴露到PersonExtern.h文件,函数实现在cpp文件中)

//
//  PersonExtern.h
//  LXFSwiftApp
//

#ifndef PersonExtern_h
#define PersonExtern_h

typedef void* CPP_Person;

#ifdef __cplusplus
extern "C"{
#endif
    /**
     *  Swift能直接使用C代码但不能直接使用C++代码,所以在写好C++代码后,要使用C代码对C++代码进行封装
     *  把C代码的函数声明暴露到这个文件,函数实现在cpp文件中
     */
    // 在这里写上C的函数声明
    // 初始化一个Person的实例
    CPP_Person person_init();
    // 调用Person实例的方法
    void person_introduceMySelf(CPP_Person person);
#ifdef __cplusplus
}
#endif

#endif /* PersonExtern_h */

3、在桥接文件中,加入PersonExtern.h引用:#import "PersonExtern.h"

4、swift中调用

let person = person_init()
person_introduceMySelf(person)

终端结果:

Hello, I am LINGLemon, my age is 12 years old. I am a boy.

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值