zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    《程序猿闭门造车》之NBPM工作流引擎
    CryptographicException异常处理方法
    nodejs简单模仿web.net web api
    Windows Mobile设备操作演示准备工作小记
    PPT定时器小记
    winDBG排错小记
    Ubuntu 16.04应用布署小记
    Ubuntu 16.04环境布署小记
    Ubuntu 16.04系统布署小记
    Dokuwiki布署小记
  • 原文地址:https://www.cnblogs.com/MayGarden/p/1674870.html
Copyright © 2011-2022 走看看