[转]COM+互操作

http://social.msdn.microsoft.com/Forums/en-US/netfx64bit/thread/674cbd6f-8ac7-4902-a7a2-5cc3d831cd5b

http://msdn.microsoft.com/en-us/library/tt0cf3sx%28VS.80%29.aspx

http://technet.microsoft.com/zh-cn/04za0hca.aspx

http://blog.csdn.net/kimmking/article/details/3445233

 

 

ActiveX controls or COM components written in .NET languages cannot be referenced by .NET applications in the

form of interop assemblies. If you "add reference" to such a TLB, or drag & drop such an ActiveX control to your .NET application, you will get an error "The ActiveX type library 'XXXXX.tlb' was exported from a .NET assembly and cannot be added as a reference.". The correct approach is to add a reference to the .NET assembly directly.

 

1       使用C#建立.net的dll

1.1    建立项目

在.net中新建一个项目:TestCom。

 

 

1.2    实现c#类

在class1.cs文件中添加一个接口和一个类:

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

 

namespace TestCom

{

    [ComVisible(true)]

    public interface iClass1

    {

        string test();

    }

 

    [ComVisible(true)]

    [ClassInterface(ClassInterfaceType.AutoDual)]  

    public class Class1 : iClass1

    {

        public string test()

        {

            return "ok";

        }

 

    }

}

 

注意接口和类上的属性,对com可见和生成com类型。

 

1.3    添加强名

 选择开始菜单中Vistual Studio目录下的Vistual Studio Tools下的Vistual Studio 命令提示。使用sn -k c:/myKey.snk生成签名文件。

在项目上右键,点击属性,选择签名,选中为程序集签名,选择myKey.snk文件。

 

 

1.4    生成解决方案

在项目目录的/TestCom/bin/Debug中可以找到TestCom.dll。至此,c#生成的.net dll已经完成。

 

 

2       生成和注册类型库

 

2.1    生成tlb类型库

在Visual Studio命令提示符下,切换到此目录。

输入tlbexp TestCom.dll /out:TestCom.tlb,提示成功导出tlb类型库文件。

 

 

 

2.2    注册类型库

输入regasm TestCom.dll /tlb: TestCom.tlb /codebase,将类型库导入到注册表。提示成功注册了类型,说明操作成功,此时TestCom .dll可以作为一个com来使用。

 

 

 

2.3    添加dll到GAC

输入gacutil /i TestCom.dll,将此.net程序集添加到GAC。

 

3       vb调用测试

3.1    创建vb项目

在vb中新建一个标准exe项目。

在项目菜单选择引用,在弹出的引用com对象列表中找到TestCom,选上。

在窗体上拖放一个按钮,双击按钮,在按钮事件里输入代码:

Dim a As New TestCom.Class1

MsgBox a.test

 

 

 

3.2    运行程序

启动项目,点击按钮,弹出对话框ok,说明调用成功。

 

 

 

 

4       asp调用测试

4.1    创建asp文件

在iis的根目录下新建一个文本文件,改名为1.asp,输入以下内容:

 

<%

SET s = CreateObject("TestCom.Class1")

Response.Write(s.test())

%>

4.2    运行程序

在ie中访问此文件,页面输出ok,说明调用成功。

 

 

 

 

posted @ 2012-12-04 22:14  chunchill  阅读(620)  评论(0编辑  收藏  举报