how do you write a c wrapper for a c++ class with inheritance

妖精的绣舞 提交于 2019-12-04 05:44:01

First, your sample should really get a proper virtual dtor.

Next, just add one free function with C-binding for each function which is part of the interface, simply delegating:

"sample.h"

#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

"sample-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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!