1 .
在
StdAfx.h
文件中加入代码
:
#import "..\MyProj\MyProj.tlb"
最后的StdAfx.h文件如下:
//
stdafx.h : include file for standard system include files,
//
or project specific include files that are used frequently, but
//
are changed infrequently
//
#if
!defined(AFX_STDAFX_H__2B646017_28AD_4CDE_9792_CB8F9A5C6B39__INCLUDED_)
#define
AFX_STDAFX_H__2B646017_28AD_4CDE_9792_CB8F9A5C6B39__INCLUDED_
#if
_MSC_VER > 1000
#pragma once
#endif
//
_MSC_VER > 1000
#define
VC_EXTRALEAN
//
Exclude rarely-used stuff from Windows headers
#include
<
afxwin.h
>
//
MFC core and standard components
#include
<
afxext.h
>
//
MFC extensions
#include
<
afxdisp.h
>
//
MFC Automation classes
#include
<
afxdtctl.h
>
//
MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include
<
afxcmn.h
>
//
MFC support for Windows Common Controls
#endif
//
_AFX_NO_AFXCMN_SUPPORT
#import
"
..\MyProj\MyProj.tlb
"
//
{{AFX_INSERT_LOCATION}}
//
Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif
//
!defined(AFX_STDAFX_H__2B646017_28AD_4CDE_9792_CB8F9A5C6B39__INCLUDED_)
编译 StdAfx.cpp
,
这样在客户端的
debug
目录下生成组件的类型库头文件
(.tlh)
和类型库实现文件
(.tli)
。
2. 在调用Dll类的头文件中加入using namespace MYPROJLib;
//
MyExeDlg.cpp : implementation file
//
#include
"
stdafx.h
"
#include
"
MyExe.h
"
#include
"
MyExeDlg.h
"
#ifdef _DEBUG
#define
new DEBUG_NEW
#undef
THIS_FILE
static
char
THIS_FILE[]
=
__FILE__;
#endif
using
namespace
MYPROJLib;
以下代码略
3.初始化COM
库:在调用Dll的类的构造函数或者相关的地方调用CreateCom(CString strComName),其中strComName为借口名字。例如MyProj.dll中的MyCom接口,则strComName为“MyProj.MyCom”即CreateCom("MyProj.MyCom");
Create函数:
BOOL CMyExeDlg::CreateCom(CString strComName)
{
int length = strComName.GetLength();
size_t aLen = length + 1;
int wLen = MultiByteToWideChar( CP_ACP, 0,strComName,aLen, NULL,0);
LPOLESTR lpFileName = new WCHAR [wLen];
MultiByteToWideChar(CP_ACP, 0,strComName,aLen,lpFileName,wLen);
HRESULT hr=CoInitialize(NULL);
CLSID clsid;
hr=CLSIDFromProgID(/**//*OLESTR("MyProj.MyCom")*/lpFileName,&clsid);
if(FAILED(hr))
{
AfxMessageBox("COM Failed");
return FALSE;
}
ptr = NULL;
hr=CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,__uuidof(IMyCom),(LPVOID*)&ptr);
return TRUE;
}
4. 在调用Dll类的头文件中定义接口: IMyCom *ptr;(其中IMyCom 为接口)
5. 调用接口的函数:例如 ptr->MyF1();
6. 释放接口:在调用Dll类的析构函数或相关的释放函数中调用 ptr->Release(); CoUninitialize();