vc6中COM对Dll的包装以及对COM的调用

本试验包括三个工程:

COM组件:OperCom ,调用Dll,实现一定的功能。

Dll:SubDll,真正的功能实现者,为com调用。

客户端:TestOperCom,用来测试com组件功能。

COM工程:

核心部分代码(调用Dll,实现功能):

// Oper.cpp : Implementation of COper
#include "stdafx.h"
#include "OperCom.h"
#include "Oper.h"
#include <windows.h>

/////////////////////////////////////////////////////////////////////////////
// COper
typedef int (*pSub)(int a, int b);
HINSTANCE hDll; 
BOOL InitialCom()
{
 hDll = LoadLibrary("..\\Debug\\SubDll.dll");

 if (hDll != NULL)
  return TRUE;

 else
  return FALSE;

}

STDMETHODIMP COper::Add(int a, int b, int *c)      //Com自己实现的功能
{
 // TODO: Add your implementation code here
 *c = a+b;
 return S_OK;
}

STDMETHODIMP COper::Sub(int a, int b, int *c)     //Com调用Dll的功能
{
 // TODO: Add your implementation code here
 BOOL bRet = InitialCom();
 
 if(bRet)
 {
  pSub m_sub = (pSub)GetProcAddress(hDll,"Sub");
  if (m_sub !=NULL)
  {
   *c = (*m_sub)(a,b);
  }
  else
      *c = 0;  

 }
 return S_OK;
}

 Dll工程:(简单起见,这里只实现一个方法Sub)

Dll工程只包含两个文件:

SubDll.h              //头文件

#ifndef SUBDLL_H
#define SUBDLL_H

extern "C" __declspec(dllexport) int Sub(int a, int b);
#endif

SubDll.cpp         //实现文件

#include "SubDll.h"


int Sub(int a, int b)
{
 return a-b;
}

 客户端:

#include <atlbase.h>
#include <comdef.h>
#import ".\OperCom.tlb" no_namespace

int main()
{
 CoInitialize(NULL);
 CLSID clsid;
 int c =0;
 CLSIDFromProgID(OLESTR("OperCom.Oper"),&clsid);
 {
  CComPtr<IOper> pGetRes;//智能指针
  pGetRes.CoCreateInstance(clsid);
  pGetRes->Sub(9,5,&c);
 }
   CoUninitialize();

   return 0;
}

原文地址:https://www.cnblogs.com/MayGarden/p/1674870.html