名詞解釋:
coclass: 是component object class的縮寫,其中包含一個或者多個interface, coclass實現(xiàn)了這些接口;
COM object: 是coclass在內存中的實例
COM server: 是一個二進制文件(DLL 或者 Exe),其中包含一個或者多個coclass
Registration(注冊): 創(chuàng)建注冊表項,告訴Windows到哪里尋找COM server的過程
Guid: 每個interface或者coclass都有一個Guid, 還會看到uuid, 跟Guid是一回事
class ID, CLSID: 用來命名一個coclass;
interface ID, IID: 用來命名一個interface;
HRESULT: 一個整型數(shù)值,用來返回成功或者錯誤的代碼
COM Library: 是操作系統(tǒng)的一部分, 當做與COM相關的事情的時候,與之交互
COM對象和標準Win32控件的區(qū)別
在使用標準win32控件的時候,首先要獲得這個控件的句柄(handle, HWND),然后用sendmessage給它發(fā)送一個消息來操控它;同樣,當控件要通知你什么消息或者給你傳遞一些數(shù)據(jù)時,它也要給你傳遞消息;
對于COM對象則不需要把消息傳來傳去.COM對象會給你一些特定的函數(shù)指針,你可以調用這些函數(shù)指針來操作COM對象;
COM對象和VTable
我們從一個簡單的C的struct開始,我們定義一個struct:
struct IExample
{
DWORD count;
char buffer[80];
};
再用typedef來簡化一下:
typedef struct
{
DWORD count;
char buffer[80];
} IEXample;
接下來,我們就可以使用這個struct了:
IExample* example;
example = (IExample*)GlobalAlloc(GMEM_FIXED, sizeof(IEXample));
example->count = 1;
example->buffer[0] = 0;
然后我們知道,struct中是可以包含函數(shù)指針的,假設我們現(xiàn)在有一個函數(shù),這個函數(shù)有個字符指針的參數(shù),返回值是long類型:
long SetString(char * str)
{
return (0);
}
這個時候我們就可以得到類似這樣的代碼:
#include <windows.h> typedef long SetStringPtr(char *); typedef struct { SetStringPtr* SetString; DWORD count; char buffer[80]; } IExample; long SetString(char *str) { return (0); } int _tmain(int argc, _TCHAR* argv[]) { IExample* example; example = (IExample*)GlobalAlloc(GMEM_FIXED, sizeof(IExample)); example->SetString = SetString; example->buffer[0] = 0; example->count = 1; long value = example->SetString("this is a test!"); return 0; }
但是,假如我們現(xiàn)在不想把函數(shù)指針直接存放在IExample內, 我們想要有一組函數(shù)指針.我們可以定義另一個struct,它的唯一的目的就是存放我們的函數(shù)指針,我們的代碼就成了這個樣子:
#include <windows.h> typedef long SetStringPtr(char *); typedef long GetStringPtr(char*, long); typedef struct { SetStringPtr* SetString; GetStringPtr* GetString; } IExampleVtbl; typedef struct { IExampleVtbl* lpVtbl; DWORD count; char buffer[80]; } IExample; long SetString(char *str) { return (0); } long GetString(char* str, long len) { return 0; } static IExampleVtbl IExample_Vtbl = {SetString, GetString}; int _tmain(int argc, _TCHAR* argv[]) { IExample* example; example = (IExample*)GlobalAlloc(GMEM_FIXED, sizeof(IExample)); example->lpVtbl = &IExample_Vtbl; example->buffer[0] = 0; example->count = 1; long value = example->lpVtbl->SetString("this is a test!"); return 0; }
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
