还只是模拟,把组件 抽取出来,通过DLL的方式调用
1.定义接口
//
// Iface.h
//
// Interfaces
interface IX : IUnknown
{
virtual void __stdcall Fx() = 0 ;
} ;
interface IY : IUnknown
{
virtual void __stdcall Fy() = 0 ;
} ;
interface IZ : IUnknown
{
virtual void __stdcall Fz() = 0 ;
} ;
// Forward references for GUIDs
extern "C"
{
extern const IID IID_IX ;
extern const IID IID_IY ;
extern const IID IID_IZ ;
}
2. 定义 IID,接口标志
//
// GUIDs.cpp - Interface IDs
//
#include <objbase.h>
extern "C"
{
// {32bb8320-b41b-11cf-a6bb-0080c7b2d682}
extern const IID IID_IX =
{0x32bb8320, 0xb41b, 0x11cf,
{0xa6, 0xbb, 0x0, 0x80, 0xc7, 0xb2, 0xd6, 0x82}} ;
// {32bb8321-b41b-11cf-a6bb-0080c7b2d682}
extern const IID IID_IY =
{0x32bb8321, 0xb41b, 0x11cf,
{0xa6, 0xbb, 0x0, 0x80, 0xc7, 0xb2, 0xd6, 0x82}} ;
// {32bb8322-b41b-11cf-a6bb-0080c7b2d682}
extern const IID IID_IZ =
{0x32bb8322, 0xb41b, 0x11cf,
{0xa6, 0xbb, 0x0, 0x80, 0xc7, 0xb2, 0xd6, 0x82}} ;
// The extern is required to allocate memory for C++ constants.
}
3. 通过 组件名,创建组件,返回IUnknown指针,模拟了 实际COM中的CoCreateInstance
//
// Create.h
//
IUnknown* CallCreateInstance(char* name) ;
//
// Create.cpp
//
#include <iostream>
#include <unknwn.h> // Declare IUnknown.
#include "Create.h"
using namespace std;
typedef IUnknown* (*CREATEFUNCPTR)() ;
IUnknown* CallCreateInstance(char* name)
{
// Load dynamic link library into process.
HINSTANCE hComponent = ::LoadLibrary(name) ;
if (hComponent == NULL)
{
cout << "CallCreateInstance:\tError: Cannot load component." << endl ;
return NULL ;
}
// Get address for CreateInstance function.
CREATEFUNCPTR CreateInstance
= (CREATEFUNCPTR)::GetProcAddress(hComponent, "CreateInstance") ;
if (CreateInstance == NULL)
{
cout << "CallCreateInstance:\tError: "
<< "Cannot find CreateInstance function."
<< endl ;
return NULL ;
}
return CreateInstance() ;
}
4. 客户端//
// Client1.cpp
// To compile, use: cl Client1.cpp Create.cpp GUIDs.cpp UUID.lib
//
#include <iostream>
#include <objbase.h>
#include "Iface.h"
#include "Create.h"
using namespace std;
void trace(const char* msg) { cout << "Client 1:\t" << msg << endl ;}
//
// Client1
//
int main()
{
HRESULT hr ;
// Get the name of the component to use.
char name[40] ;
cout << "Enter the filename of a component to use [Cmpnt?.dll]: " ;
cin >> name ;
cout << endl ;
// Create component by calling the CreateInstance function in the DLL.
trace("Get an IUnknown pointer.") ;
IUnknown* pIUnknown = CallCreateInstance(name) ;
if (pIUnknown == NULL)
{
trace("CallCreateInstance Failed.") ;
return 1 ;
}
trace("Get interface IX.") ;
IX* pIX ;
hr = pIUnknown->QueryInterface(IID_IX, (void**)&pIX) ;
if (SUCCEEDED(hr))
{
trace("Succeeded getting IX.") ;
pIX->Fx() ; // Use interface IX.
pIX->Release() ;
}
else
{
trace("Could not get interface IX.") ;
}
trace("Release IUnknown interface.") ;
pIUnknown->Release() ;
system("pause");
return 0 ;
}
5. 省略了 组件 定义、编译
对于CMPNT1.CPP和CMPNT1.DEF,通过nmake 命令,编译成 CMPNT1.dll 动态链接库
放入 客户端文件夹下,即可调用