0

虚拟表是函数指针的数组。我如何实现它,因为每个函数都有不同的签名?

4

3 回答 3

4

You don't implement it.

The compiler generates it (or something with equivalent functionality), and it's not constrained by the type system so it can simply store the function addresses and generate whatever code is needed to call them correctly.

You can implement something vaguely similar using a struct containing different types of function pointer, rather than an array. That's quite a common way of implementing dynamic polymorphism in C; for example, the Linux kernel provides polymorphic behaviour for file-like objects by defining an interface along the lines of:

struct fileops {
    int (*fo_read)  (struct file *fp, ...);
    int (*fo_write) (struct file *fp, ...);
    // and so on
};
于 2012-08-21T10:12:21.153 回答
0

If functions in a virtual table have different signatures, you'll have to implement it as a structure type containing members with heterogeneous types.

Alternately, if you have other information telling you what the signatures are, you can cast a function pointer to another function pointer type, as long as you cast it back to the correct type before calling it.

于 2012-08-21T10:12:11.293 回答
0

如果您在编译时知道每个函数,那么您可以使用不同类型的函数指针的结构(但是,如果您在编译时知道每个函数,为什么不只使用带有虚拟方法的类呢?)。

如果您想在运行时执行此操作,那么一个数组void*可能就足够了。您需要在存储它们时将指针转换为输入,然后在调用它们之前再次转换(到正确的类型)。当然,您需要在其他地方跟踪函数类型(包括调用约定)。

在不知道您打算如何处理的情况下,很难给出更有用的答案。


在代码中实现 vtable 是有正当理由的。它们是一个实现细节,因此您需要针对已知的 ABI 而不仅仅是“C++”。我所做的唯一一次是在运行时动态创建新的 COM 类的实验(COM 对象的 ABI 预期是一个指向 vtable 的指针,其中包含遵循__stdcall调用约定的函数,其中前 3 个函数实现IUnknown接口)。

于 2012-08-21T10:37:01.240 回答