巧用C#做中間語言 實現Java調用.net DLL的方法
51CTO曾經為大家講過“Java與.NET的WebServices相互調用”,但是如何實現Java調用.net DLL的方法呢?我們在網上搜索了一番,也沒找到啥東西,甚至看到人揚言此事絕無可能。本文將詳細為大家介紹一個java調用.net DLL的方法,以實現特殊的客戶的特殊要求:“在Java項目中必須使用其提供的用.net寫的DLL加密機制!”
環境與工具:
◆.net framework 3.5 C#
◆java jdk1.5, Tomcat 5.5
◆jacob-1.15-M3
實現例子:
一、C# 制作Com組件
新建一個Class 項目,取名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 "測試 | "+str+"|"+str2;
- }
- }
- }
打開 Project--> Properties菜單 在Application標簽中打開 Assembly Information 將Make assembly Com-Visible一項選中。再切換到Build標簽將 Register for COM interop一項選中。
Guid的生成:打開Visual Studio Command Prompt 輸入guidgen 命令調出工具。類型選擇Registry Format,點擊New Guid,然后COPY出來。
[DispId(1)]為函數的標識。如果有多個函數可相應的在函數前面加[DispId(2)], [DispId(3)]…
編譯程序Debug目錄中會生成 TestCom.dll 和TestCom.tlb
手工注冊Com方法:
打開Visual Studio Command Prompt進入Debug目錄,運行命令注冊:regasm TestCom.DLL /tlb:TestCom.tlb
二、Java調用Com
部署jacob
◆在開發環境中引入jacob.jar
◆拷貝jacob-1.15-M3-x86.dll 文件到 C:\Windows\System32目錄,如果是Web應用的話還需要拷貝到jdk1.5.0_16\bin目錄(jdk安裝目錄下的bin目錄)
java調用代碼
代碼
- 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","哥是***個參數","哥是第二個參數");
- String str = var.toString(); //返回值
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
這便完成了Java調用.net DLL的方法!
原文地址:http://www.cnblogs.com/windsor/archive/2010/06/17/1759289.html
【編輯推薦】