8分钟
2.8.2.4 封装C++对象改进
在前面的封装C++对象的实现中,每次通过new创建一个Person实例需要进行两次内存分配:一次是针对C++版本的Person,再一次是针对Go语言版本的Person。其实C++版本的Person内部只有一个person_handle_t类型的id,用于映射Go对象。我们完全可以将person_handle_t直接当中C++对象来使用。
下面时改进后的包装方式:
extern "C" {
#include "./person_capi.h"
}
struct Person {
static Person* New(const char* name, int age) {
return (Person*)person_new((char*)name, age);
}
void Delete() {
person_delete(person_handle_t(this));
}
void Set(char* name, int age) {
person_set(person_handle_t(this), name, age);
}
char* GetName(char* buf, int size) {
return person_get_name(person_handle_t(this), buf, size);
}
int GetAge() {
return person_get_age(person_handle_t(this));
}
};
我们在Person类中增加了一个叫New静态成员函数,用于创建新的Person实例。在New函数中通过调用person_new来创建Person实例,返回的是person_handle_t
类型的id,我们将其强制转型作为Person*
类型指针返回。在其它的成员函数中,我们通过将this指针再反向转型为person_handle_t
类型,然后通过C接口调用对应的函数。
到此,我们就达到了将Go对象导出为C接口,然后基于C接口再包装为C++对象以便于使用的目的。
学员评价