一、引言
實驗目的:
構建一個com組件,該組件存儲了10000個12位的驗證碼;輸入一個驗證碼,組件返回該驗證碼是否正確(是否是10000個其中之一);輸入一個字符串,返回一個對應的映射的驗證碼(映射方法自己定義)。
二、環境
- Windows 10 ×64
- Visual Studio 2015
- IDEA 2018.1.5
- jacob-1.19
三、實驗步驟
1.C#寫com組件
以管理員身份運行VS
新建->項目->Visual C#->選擇【類庫】,名稱自定義:MyComToJava,點擊【確定】

重命名cs文件:MyComToJava.cs,可自定義。彈窗選擇【是】

右鍵點擊工程->屬性->應用程序->程序集信息->“使程序集COM可見(M)”打上勾,點擊【確定】



生成->“為COM互操作注冊(C)”打上勾,保存

簽名->“為程序集簽名(A)”打上勾->新建簽名MyComToJava->取消勾選“使用密碼保護密鑰文件”,點擊【確定】,保存

通過點擊工具->創建 GUID->選擇5->新建 GUID->復制->替換C#代碼中的兩個 GUID 值


C#代碼:C#代碼中必須定義了接口,才可以按照此方法實現調用。一定要寫ProgId。
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace MyComToJava { [Guid("E2032C8D-2E32-4415-8E8C-CFACBCAAADF3")] public interface IVerifyCode { string CheckVerifyCode(string str); string StrToVerifyCode(string str); string GetVerifyCode(int i); } [Guid("BF4EFCF8-8F67-46F2-A84F-E88C8C3DD7A7"),ClassInterface(ClassInterfaceType.None)] [ProgId("MyComToJava.Application")] public class VerifyCode : IVerifyCode { int number = 10; int length = 12; List<string> list; public VerifyCode() { list = new List<string>(); CreateVerifyCode(number,length); } //生成10000個12位的驗證碼 public List<string> CreateVerifyCode(int number,int length) { while (list.Count < number) { String code = getRandom(length); if (!list.Contains(code)) { list.Add(code); } } return list; } private static string getRandom(int length) { Random rand = new Random(); string validateStr = ""; char[] validateChar = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8','9','a','b','c', 'd','e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; for (int i=0;i < length; i++)