背景:
近日一個(gè)java的項(xiàng)目,客戶要求項(xiàng)目中必須使用其提供的加密機(jī)制,扔給了兩個(gè).net寫的DLL。網(wǎng)絡(luò)上搜了一圈也沒找到啥東西,甚至看到人揚(yáng)言此事絕無可能。郁悶當(dāng)中考慮了一個(gè)思路。用C#做一個(gè)Com,調(diào)用客戶提供的DLL實(shí)現(xiàn)加密解密的方法,然后提供給java使用。經(jīng)過一番搗騰,最后證實(shí)可行。
環(huán)境與工具:
1、.net framework 3.5 C#
2、java jdk1.5, Tomcat 5.5
3、jacob-1.15-M3
實(shí)現(xiàn)例子:
一、C# 制作Com組件
新建一個(gè)Class 項(xiàng)目,取名TestCom
代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace TestCom
{
[Guid("E9BCF867-CD81-40d0-9591-ED28D1ED2B53")]
public interface IEncrypt
{
[DispId(1)]
string GetEncrypt(string str,string str2);
}
[Guid("33A6E58D-E1F5-4b53-B2E2-03B9F8BA2FAD"), ClassInterface(ClassInterfaceType.None)]
public class Encrypt:IEncrypt
{
public Encrypt(){}
public string GetEncrypt(string str,string str2)
{
return "測(cè)試 | "+str+"|"+str2;
}
}
}
打開 Project--> Properties菜單 在Application標(biāo)簽中打開 Assembly Information 將Make assembly Com-Visible一項(xiàng)選中。再切換到Build標(biāo)簽將 Register for COM interop一項(xiàng)選中。
Guid的生成:打開Visual Studio Command Prompt 輸入guidgen ming令調(diào)出工具。類型選擇Registry Format,點(diǎn)擊New Guid,然后COPY出來。
[DispId(1)]為函數(shù)的標(biāo)識(shí)。如果有多個(gè)函數(shù)可相應(yīng)的在函數(shù)前面加[DispId(2)], [DispId(3)]…
編譯程序Debug目錄中會(huì)生成 TestCom.dll 和TestCom.tlb
手工注冊(cè)Com方法:
打開Visual Studio Command Prompt進(jìn)入Debug目錄,運(yùn)行ming令注冊(cè):regasm TestCom.DLL /tlb:TestCom.tlb
二、java 調(diào)用 Com
部署jacob
1、在開發(fā)環(huán)境中引入jacob.jar
2、拷貝jacob-1.15-M3-x86.dll 文件到 C:/Windows/System32目錄,如果是Web應(yīng)用的話還需要拷貝到j(luò)dk1.5.0_16/bin目錄(jdk安裝目錄下的bin目錄)
java調(diào)用代碼
代碼
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
ActiveXComponent dotnetCom = null;
dotnetCom = new ActiveXComponent("TestCom.Encrypt");
Variant var = Dispatch.call(dotnetCom,"GetEncrypt","哥是第一個(gè)參數(shù)","哥是第二個(gè)參數(shù)");
String str = var.toString(); //返回值
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
新聞熱點(diǎn)
疑難解答