首页 > 解决方案 > 通过函数指针的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) 

标签: c++cabivtable

解决方案


推荐阅读