IDL math.idl文件如下:
import "objidl.idl"; [ object, uuid(C9BAF4B4-0637-404e-824A-631F5B80FED5) ] //生成的时候要在项目设置里面MIDL选项里吧MKTYPLIB..兼容给取消 interface IMath:IUnknown { HRESULT Add(long nAdd1,long nAdd2,long *pnAdd); HRESULT Sub(long nSub1,long nSub2,long *pnSub); }
// ImpMath.cpp: implementation of the CImpMath class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ImpMath.h" #include "math_i.c" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CImpMath::CImpMath() { m_nRef=0; } CImpMath::~CImpMath() { } //IUnknown函数实现 STDMETHODIMP CImpMath::QueryInterface(REFIID iid,void** ppiObject) { if(iid==IID_IUnknown){ *ppiObject=static_cast<IUnknown *>( this ); }else if(iid==IID_IMath) { *ppiObject=static_cast<IMath *>(this); }else{ *ppiObject=NULL; return E_FAIL; } AddRef(); return S_OK; } STDMETHODIMP_(ULONG) CImpMath::AddRef(){ //使用原子锁 避免多线程访问出错 InterlockedIncrement(&m_nRef); return m_nRef; } STDMETHODIMP_(ULONG) CImpMath::Release(){ InterlockedIncrement(&m_nRef); if(m_nRef==0){ delete this; } return m_nRef; } STDMETHODIMP CImpMath::Add(long nAdd1,long nAdd2, long * pnAdd) { if(pnAdd==NULL){ return E_INVALIDARG; } *pnAdd=nAdd1+nAdd2; return S_OK; } STDMETHODIMP CImpMath::Sub(long nSub1,long nSub2, long * pnSub) { *pnSub=nSub1+nSub2; return S_OK; }
// COMInterface.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #include "ImpMath.h" BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } IUnknown * CreateInstance() { //创建对象 CImpMath *pMath=new CImpMath; //获取接口 IUnknown *piUnknown = NULL; pMath->QueryInterface(IID_IUnknown,(LPVOID*)&piUnknown); //返回接口 return piUnknown; }
def文件
LIBRARY "COMInterface" EXPORTS CreateInstance @1
// UserComIf.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "../COMInterface/math.h" #include "../COMInterface/math_i.c" typedef IUnknown *(*CREATEINSTANCE)(); IMath * GetMath(){ HMODULE hDll=(HMODULE)LoadLibrary("COMInterface.dll"); CREATEINSTANCE CreateInstance=(CREATEINSTANCE)GetProcAddress(hDll,"CreateInstance"); //创建接口 IUnknown * piUnknown=CreateInstance(); IMath * piMath=NULL; HRESULT nRet=piUnknown->QueryInterface(IID_IMath,(LPVOID*)&piMath); //释放接口 判断返回值 piUnknown->Release(); if(FAILED(nRet)){ printf("cannt find IMath\n"); return NULL; } //返回IMath接口 return piMath; } int main(int argc, char* argv[]) { //获取接口 IMath *piMath=GetMath(); //使用接口 long nAdd=0; piMath->Add(100,100,&nAdd); printf("%d\n",nAdd); //释放接口 //piMath->Release(); return 0; }程序下载 :http://pan.baidu.com/s/1i3A6U25