如何解决通过函数指针的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's 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。