如何编写与继承一个C ++类C包装 [英] how do you write a c wrapper for a c++ class with inheritance
本文介绍了如何编写与继承一个C ++类C包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想知道是否有创建一个C ++类,有继承一个C API封装的方式。
I was just wondering if there was a way to create a c wrapper API for a c++ class that has inheritance.
考虑以下几点:
class sampleClass1 : public sampleClass{
public:
int get() { return this.data *2; };
void set(int data);
}
class sampleClass : public sample{
public:
int get() { return this.data; }
void set(int data) {this.data = data; }
}
class sample {
public:
virtual int get();
virtual void set(int data);
private:
int data;
}
如何将我包裹sampleClass1,使其在C环境???
How would I wrap the sampleClass1 to make it work in a c context ???
感谢,
推荐答案
首先,你的样品
真的应该得到适当的虚拟
析构函数。
First, your sample
should really get a proper virtual
dtor.
接下来,只需添加一个免费功能的C-约束力的是接口的一部分各项功能,只需委托:
Next, just add one free function with C-binding for each function which is part of the interface, simply delegating:
#ifdef __cplusplus
extern "C" {
#endif
typedef struct sample sample;
sample* sample_create();
sample* sample_create0();
sample* sample_create1();
void sample_destroy(sample*);
int sample_get(sample*);
void sample_set(sample*, int);
#ifdef __cplusplus
}
#endif
样本c.cpp
#include "sample.h" // Included first to find errors
#include "sample.hpp" // complete the types and get the public interface
sample* sample_create() {return new sample;}
sample* sample_create0() {return new sampleClass;}
sample* sample_create1() {return new sampleClass1;}
void sample_destroy(sample* p) {delete p;}
int sample_get(sample* p) {return p->get();}
void sample_set(sample* p, int x) {p->set(x);
sample.hpp
// Your C++ header here, with class definition
sample.cpp的
#include "sample.hpp" // Included first to find errors
// Implement the class here
这篇关于如何编写与继承一个C ++类C包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文