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.