繁体   English   中英

你如何为继承的c ++类编写一个c包装器

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

我只是想知道是否有办法为具有继承的c ++类创建ac包装器API。

考虑以下:

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以使其在ac上下文中工作?

谢谢,

首先,你的sample应该真正得到一个合适的virtual dtor。

接下来,只需为每个函数添加一个带有C绑定的自由函数,该函数是接口的一部分,只需委托:

“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

“样品-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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM