在vb和asp中调用c#生成的.net的dll

来源:互联网 发布:学java要先学c语言吗 编辑:程序博客网 时间:2024/05/17 04:14

摘要:本文阐述了在vb和asp调用c#生成的.netdll的方法和步骤。
 
1       使用C#建立.netdll
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来使用。 

 

 

 

 

 

参考文章:http://blog.csdn.net/zhaili1978/archive/2008/10/11/3057576.aspx


3     asp调用测试
3.1    创建asp文件
在iis的根目录下新建一个文本文件,改名为1.asp,输入以下内容: 
<% 
SET s = CreateObject("TestCom.Class1") 
Response.Write(s.test()) 
%>

 

注:如果项目中引用了其他没有源码的dll文件,并且此dll文件是没有强名称的程序集,则编译时会出现类似 "Assembly generation failed -- 引用的程序集 'xxxxxxxxxxx' 没有强名称" 这样的错误。

 

解决方法:

 

在Visual Studio命令提示符下:

1 .创建一个新的随机密钥对:
sn -k Interop.Scripting.snk
2 .反编译目标程序集
ildasm Interop.Scripting.dll /out=Interop.Scripting.il
3 .重新编译,附带强命名参数
ilasm Interop.Scripting.il /dll /resource=Interop.Scripting.res /key=Interop.Scripting.snk /optimize
4 .验证签名信息
sn -v Interop.Scripting.dll


OK,将生成的dll文件重新引入到项目中然后编译。

 

 


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

原创粉丝点击