gpt4 book ai didi

c++ - 你如何为具有继承的 C++ 类编写 C 包装器

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:25 24 4
gpt4 key购买 nike

我只是想知道是否有办法为具有继承的 C++ 类创建一个 C 包装器 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 以使其在 c 上下文中工作???

谢谢,

最佳答案

首先,您的示例 应该真正获得适当的虚拟 dtor。

接下来,只需为作为接口(interface)一部分的每个函数添加一个具有 C 绑定(bind)的自由函数,简单地委托(delegate):

“示例.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);

“示例.hpp”

// Your C++ header here, with class definition

“示例.cpp”

#include "sample.hpp" // Included first to find errors
// Implement the class here

关于c++ - 你如何为具有继承的 C++ 类编写 C 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com