本篇文章介绍了如何用C#写一个简单的COM组件(Dll)。
1、新建一个C# Class Library项目“CSCOMTest”
2、项目中,新增一个接口文件IJustATestCOM.cs,Guid要自己生成
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace CSCOMTest { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("A5377871-3334-4679-A3CD-84312B1DCD3E")] public interface IJustATestCOM { int Add(int a, int b); String SayHiTo(String someOne); } }
3、项目中,新增一个类文件JustATestCOM.cs,Guid要自己生成
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace CSCOMTest { [ComVisible(true)] [Guid("A6E4F456-32C1-4C8E-9171-D616B5DA1E20")] [ProgId("CSCOMTest.JustATestCOM")] public class JustATestCOM : IJustATestCOM { public int Add(int a, int b) { return a + b; } public String SayHiTo(String someOne) { return "Hi " + someOne + "!"; } } }
4、项目属性->Application->Assembly Infomation->Make Assembly COM-Visible->打勾
5、项目属性->Signing->Sign the assembly->打勾
项目属性->Signing->Choose a strong name key file->New
6、编译
7、注册
#这里一定要用正确版本的gacutil及RegAsm C:\VBS\DNFW4\gacutil.exe /i CSCOMTest.dll C:\VBS\DNFW4\RegAsm.exe CSCOMTest.dll
8、反注册
#这里一定要用正确版本的gacutil及RegAsm C:\VBS\DNFW4\gacutil.exe /u CSCOMTest C:\VBS\DNFW4\RegAsm.exe /u CSCOMTest.dll
9、调用测试
'发生错误时,继续运行 On Error Resume Next '清除错误状态 Err.Clear Set Obj=CreateObject("CSCOMTest.JustATestCOM") '输出错误信息 If Err.Number <> 0 Then WScript.Echo "Error: " & Err.Number WScript.Echo "Error (Hex): " & Hex(Err.Number) WScript.Echo "Source: " & Err.Source WScript.Echo "Description: " & Err.Description 'Err.Clear '退出程序 WScript.Quit(Err.Number) End If 'On Error Goto 0 WScript.Echo obj.Add(1,2) WScript.Echo obj.SayHiTo("dcom") set obj=Nothing
10、生成tlb文件
regasm CSCOMTest.dll /tlb:CSCOMTest.tlb