c++ - 通过函数指针的C结构调用C++虚函数
问题描述
我正在为 C++ 类创建一个 C 包装器:
class IObject {
public:
virtual int getValue() const;
virtual ~IObject() = default;
};
class Object: public IObject {
public:
virtual int getValue() const { return 123; }
};
受openh264 的 C API启发,我有以下代码:
// object.h
#pragma one
#ifdef __cplusplus
class IObject {
public:
virtual int getValue() const = 0;
virtual ~IObject() = default;
};
extern "C" {
#else
typedef struct IObjectVtable IObjectVtable;
typedef IObjectVtable const* IObject;
struct IObjectVtable {
int (*getValue)(IObject*);
};
#endif
int makeObject(IObject**);
int freeObject(IObject*);
#ifdef __cplusplus
} // extern "C"
#endif
// object.cpp
#include "object.h"
class Object : public IObject {
public:
virtual int getValue() const override { return 123; }
};
extern "C" {
int makeObject(IObject** obj) {
*obj = new Object;
if (*obj == nullptr) {
return 1;
}
return 0;
}
int freeObject(IObject* obj) {
delete obj;
return 0;
}
}
在 main.c 中,我使用 Object 如下:
#include <stdio.h>
#include "object.h"
int main() {
IObject* obj;
makeObject(&obj);
printf("%d\n", (*obj)->getValue(obj)); /** Calling getValue */
freeObject(obj);
return 0;
}
代码编译并正确打印“123”,但我需要将 obj 作为 getValue() 的参数传递。是否有可能避免这种情况,即简单地调用obj->getValue()
?
根据文档,openh264 可以做到这一点,但我不明白它是如何/为什么工作的:
ISVCDecoder *pSvcDecoder; //similar to IObject* obj;
WelsCreateDecoder(&pSvcDecoder); //similar to makeObject(&obj);
pSvcDecoder->Initialize(&sDecParam); //similar to obj->getValue();
// not (*obj)->getValue(obj)
解决方案
推荐阅读
- javascript - 支持从pdf中提取向量点
- python - 打印一定数量字符的函数
- statistics - 在这种情况下我应该如何处理丢失的数据?
- python - 如何将字典中的单个值与熊猫数据框中的单个值进行比较?
- php - 使用 Laravel Excel 和视图导出多张工作表,每张工作表有 100 条记录
- logstash - 日志存储;当添加新配置文件以同步 postgres 数据时,logstash 停止工作
- javascript - React js - useState 在 onChange Form 函数内部和外部返回不同的值
- javascript - 如何在反应js中附加2个不同的数组
- arrays - 使用 numpy Python 过滤日期时间索引
- python-3.x - Python - 带有 pirebase 的 Firebase。order_by_child 的问题