巧用C#做中繼語言 實現Java調用.net DLL

來源:互聯網
上載者:User
巧用C#做中繼語言 實現Java調用.net DLL時間:2010-08-11 06:16來源:未知作者:壹號編輯點擊:3次

本文將詳細為大家介紹一個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的方法!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.