读《COM原理与应用》第二章随笔(模似的虚函数表)
今天下了这本书,看到第二章到半,书中用C描述了一个虚函数表的过程,不过代码不完全,所以就写了个,
刚刚接触COM~
/*
* pVtable vtable
* 接口指针 ---> 虚函数表指针 ---> 指针函数1 --->
* 指针函数2 ---> 对象实现
* 指针函数3 --->
*/
// 模似的虚函数表
#include <stdio.h>
#include <stdlib.h>
// 前向声明
struct IDictionaryVtable;
// 模似接口指针
struct IDictionary
{
// 虚函数表指针
IDictionaryVtable *pVtable;
};
// 模拟的虚函数表
struct IDictionaryVtable
{
bool (*Initialize)( IDictionary *pThis );
bool (*LoadLibrary)( IDictionary *pThis, char *source );
bool (*FreeLibrary)( IDictionary *pThis );
};
void InitVtable( IDictionary *pInterface );
bool InitFoo( IDictionary *pThis );
bool LoadFoo( IDictionary *pThis, char *pString );
bool FreeFoo( IDictionary *pThis );
int main()
{
// 实现接口指针
IDictionary *pi = (IDictionary*) malloc( sizeof( IDictionary ) );
InitVtable( pi );
printf( "pi: %X\n" );
printf( "pi->pVtable: %X\n", pi->pVtable );
pi->pVtable->Initialize( pi );
pi->pVtable->LoadLibrary( pi, "Phoebe" );
pi->pVtable->FreeLibrary( pi );
return 0;
}
// 初始化虚函数表
void InitVtable( IDictionary *pInterface )
{
pInterface->pVtable = (IDictionaryVtable*) malloc( sizeof( IDictionaryVtable ) );
pInterface->pVtable->Initialize = InitFoo;
pInterface->pVtable->LoadLibrary = LoadFoo;
pInterface->pVtable->FreeLibrary = FreeFoo;
}
// 初始化过程
bool InitFoo( IDictionary *pThis )
{
printf( "Init function: pThis->pVtable: %X\n", pThis->pVtable );
return true;
}
// 加载过程
bool LoadFoo( IDictionary *pThis, char *pString )
{
printf( "Load function: pThis->pVtable: %X pString: %s\n", pThis->pVtable, pString );
return true;
}
// 释放过程
bool FreeFoo( IDictionary *pThis )
{
printf( "Free function: pThis->pVtable: %X\n", pThis->pVtable );
return true;
}