通过函数指针的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 (将#修改为@)