zoukankan      html  css  js  c++  java
  • vc6中COM对lib的包装以及对COM的调用

    本实验包括三个工程:

    lib、COM、Test工程。

    lib实现一定功能(为一个静态库工程);

    COM对其进行包装;

    Test为测试程序。

    lib:包含两个文件LibOper.h和LibOper.cpp

    LibOper.h

    #ifndef LIB_OPER_H
    #define LIB_OPER_H

    extern "C" int add(int x, int y);
    #endif

    LibOper.cpp

    #include "LibOper.h"

    int add(int x, int y)
    {
     return x+y;
    }

    COM:主要代码

    // Oper.cpp : Implementation of COper
    #include "stdafx.h"
    #include "WrapOperLibCOM.h"
    #include "Oper.h"
    #include "LibOper.h"         //注意:静态库,需要头文件!

    /////////////////////////////////////////////////////////////////////////////
    // COper
    #pragma comment(lib,"..\\debug\\LibOperationForCom.lib")  //需要导入库!

    int Initialize()
    {
     return 0;
    }
    void Uninitial()
    {
     return;
    }

    STDMETHODIMP COper::AddOper(int a, int b, int *c)
    {
     // TODO: Add your implementation code here
     *c = add(a,b);
     return S_OK;
    }

    TEST:主要代码

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

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

    附录:

    快速创建COM详细步骤:

    一、创建模型(工程) MyProj
    VC++6.0工作平台中,点击菜单 File 下的 New 菜单项,在出现的 New 对话框中选中 Projects 卡片,在列表框中选中 ATL COM  AppWizard(活动模板库组件导航)。  

    Project Name 编辑框中输入项目名如 MyProj ,并选择合适的 Location 后,按确认按钮进入下一个对话框:ATL  COM  Appwizard  -  step 1 of  1,在 Server Type 中选择 Dynamic  Link  Library [ DLL ],即进程内服务器,这是最快的组件。
    选中 Support  MFC 选择项。
    在按下 Finish Ok 按钮后,一个组件的框架已经建立。


    二、给模型增加组件MyCom
    VC++ 菜单 Insert 中选中 New ATL  Object…菜单项,出现 ATL Object  Wizard 对话框。
    在左边的 Category 中选择 Objects,右边的 Objects 中选中 Simple  Object 项。按 Next 按钮。

    在出现的 ATL Object  Wizard 属性对话框中 Names 卡片中的八个编辑框中左上方的 Short Name 编辑框中输入短名如 MyCom ,其他七个编辑框的内容会自动生成。然后按确认按钮退出。


    三、给组件增加方法(函数) MyF1MyF2MyF3MyF4
    VC++工作平台的左边的 Workspace ClassView 卡片中找到接口 IMyCom 项,按右键,在出现的快捷菜单中选择 Add  Method …,出现 Add  Method  to Interface 对话框,在对话框中输入要增加的函数的函数名、参数和返回值类型。然后,按确认按钮退出。

    其余参见细说COM篇。

  • 相关阅读:
    第六周
    第五周(实验报告)
    第四周(实验报告)
    第三周(实验报告)
    Java第二周学习总结
    第一周
    2019课程总结
    第十四周课程总结
    第十三周总结
    第十二周总结
  • 原文地址:https://www.cnblogs.com/MayGarden/p/1709219.html
Copyright © 2011-2022 走看看