C++ 调用 C#写的COM (基于VS2008)

来源:互联网 发布:游戏ui网络班 编辑:程序博客网 时间:2024/04/30 18:04

一:c#创建COM

1,使用VS2008 创建一个C# class library

2,添加一个接口 IMyCOMInterface ,注意接口的属性必须是Public 的

3,添加一个类,MyCOMClass 这个类继承于上面定义的IMyCOMInterface,注意这个类也必须是public 的

4,为接口和类添加成员函数

5,设置接口的guid 属性 ,guid 通过 VS自带的工具生成

6,设置class 的guid

7,设置class 的class interface type 属性

最后代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace CShapeWithCPlus
{
    [Guid("8E4845D7-45F9-4789-B58D-61AB0CB11232")]
    public interface IMyCOMInterface
    {
        void ShowDialog();
    }
    [Guid("227FEF35-99B1-4ec3-BF19-952F5BA93B2B")]
    [ClassInterface(ClassInterfaceType.None)]
    public class MyCOMClass:IMyCOMInterface
    {
        public MyCOMClass()
        {
        }
        public void ShowDialog()
        {
            Form1 frm = new Form1();
            frm.ShowDialog();
        }
    }
}

8,设置SN file  ,打开C#的工程属性,切换到“签名”页

9,注册COM ,打开工程属性窗口,切换到“生成”页,选中 为COM互操作注册

10,编译生成dll

11,调用 下面的命令 RegAsm.exe xxxxxx.dll /tlb:xxxxxx.tlb / codebase  生成tlb 文件

 

二:C++ 调用COM

1,建立C++程序

2,import “../xxxxx.tlb”

3,  使用上面C#定义的命名空间 CShapeWithCPlus

4,基本代码如下;

#import "D:/mytest/CShapeWithCPlus/CShapeWithCPlus/bin/Debug/CShapeWithCPlus.tlb" raw_interfaces_only
using namespace CShapeWithCPlus;

 

void DoCom()
{
    HRESULT hr = CoInitialize(NULL);

    IMyCOMInterfacePtr pCom(__uuidof(MyCOMClass));

    pCom->ShowDialog();

    CoUninitialize();

}