Comdll 的编写 inface.h ---------------------- #ifdef _INFACE_H #else #define _INFACE_H #include <objbase.h> interface IX:public IUnknown { virtual ULONG __stdcall fx()=0; }; interface IY:public IUnknown { virtual void __stdcall fy()=0; }; interface IZ:public IUnknown { virtual void __stdcall fz()=0; }; class CA:public IX { virtual HRESULT __stdcall QueryInterface (const IID & riid,void **ppv); virtual ULONG __stdcall AddRef(); virtual ULONG __stdcall Release(); virtual ULONG __stdcall fx(); public: CA(); ~CA(); private: long m_cRef; }; extern "C" { const IID IID_IX; const IID IID_IY; const IID IID_IZ; } #endif ------------------ compnt1.cpp ---------------------------------- #include "inface.h" #include <objbase.h> CA::CA() { m_cRef=0; } CA::~CA() { OutputDebugString("~ destructor \n"); } HRESULT __stdcall CA::QueryInterface (const IID & riid,void **ppv) { if(riid==IID_IUnknown) { *ppv=static_cast<IX*>(this); } else if(riid==IID_IX) { *ppv=static_cast<IX*>(this); } /* else if(riid==IID_IY) { *ppv = static_cast<IY*>(this); }*/ else { *ppv=NULL; return E_NOINTERFACE; } static_cast<IUnknown *>(*ppv)->AddRef(); return S_OK; } ULONG __stdcall CA::AddRef() { return InterlockedIncrement(&m_cRef); } ULONG __stdcall CA::Release() { return InterlockedDecrement(&m_cRef); } ULONG __stdcall CA::fx() { long a=10; return a; } extern "C" IUnknown * CreateInstance() { IUnknown *pI = static_cast<IX*>(new CA()); pI->AddRef(); return pI; } ----------------------- guids.cpp ------------------------------ #include <objbase.h> // {73373F3A-716D-488b-A821-2A0E963B6285} extern const GUID IID_IX = { 0x73373f3a, 0x716d, 0x488b, { 0xa8, 0x21, 0x2a, 0xe, 0x96, 0x3b, 0x62, 0x85 } }; // {D8FED3FB-31D6-48c0-8FBA-E1B613281D36} extern const GUID IID_IY = { 0xd8fed3fb, 0x31d6, 0x48c0, { 0x8f, 0xba, 0xe1, 0xb6, 0x13, 0x28, 0x1d, 0x36 } }; // {8532846B-94E5-4a10-A632-36A49C5D5D76} extern const GUID IID_IZ = { 0x8532846b, 0x94e5, 0x4a10, { 0xa6, 0x32, 0x36, 0xa4, 0x9c, 0x5d, 0x5d, 0x76 } }; ---------------- comdll.def //模块定义软件 -------------------------------------------------- LIBRARY "Comdll" EXPORTS CreateInstance @1 -------------------------------------------------------- 在 MFC 的中 结合 #include "inface.h" #include "WinDef.h" IUnknown * CallCreateInstance(char * name) { typedef IUnknown * (* fun)(); fun func=NULL; HMODULE hMoudle; hMoudle=::LoadLibrary(name); //"Comdll.dll" if(hMoudle) { func=(fun)::GetProcAddress(hMoudle,"CreateInstance"); if(func) { return func(); } else { AfxMessageBox("func = NULL"); } } else { AfxMessageBox("DLL faild"); } return NULL; } void CCOMDlltest1Dlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 //OnOK(); char buf[30]; sprintf(buf,"%s","Comdll.dll"); IUnknown *pi=CallCreateInstance(buf); IX * ix; pi->QueryInterface(IID_IX,(void **)&ix); CString str; str.Format("%ld",ix->fx()); MessageBox(str); //typedef } |
|
来自: 水中麒麟 > 《com(组建对象)》