实例说明java调用vb的dll(读取cpu序列号)
实例说明java调用vb的dll(读取cpu序列号)
2007-07-06 16:20
?
?
【实例】java调用dll的文档搜了不少,发现都不完整,或者说的不够详细,这里通过自己的实际操作,并将过程做了整理,通过实例说明java如何用jacob调用dll里的函数。
由于某系统加密需要,需要实现从dll里实现某些功能(比如获取当前CPU序列号),并在Java中调用该函数。
(一)准备工作:需要用到文件有:jacob.dll和jacob.jar分别放到jdk/bin下和class_path下。文件下载地址:
(二)建立一个VB的Activex Dll 工程,命名为名为getCPU,自动生成Class1文件(工程名字和类名建议用英文名,以防调用时编码出问题),并添加代码如下:
Private Type OSVERSIONINFO
??????????????????? dwOSVersionInfoSize???? As Long
??????????????????? dwMajorVersion???? As Long
??????????????????? dwMinorVersion???? As Long
??????????????????? dwBuildNumber???? As Long
??????????????????? dwPlatformId???? As Long
??????????????????? szCSDVersion???? As String * 128???????????????????? '?????? Maintenance???? string???? for???? PSS???? usage
??? End Type
??? Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (lpVersionInformation As OSVERSIONINFO) As Long
??? Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
????
??? Public Function GetCPUid(para As String) As String
????
??????????? On Error GoTo doError
????????????
??????????? Dim len5?????? As Long, aa???????? As Long
??????????? Dim cmprName?????? As String
??????????? Dim Computer?????? As String
??????????? Dim CPUs?????? As Object, MyCpu???????? As Object
??????????? Dim osver?????? As OSVERSIONINFO
??????????? Dim SerialNo?????? As String
????
??????????? '取得Computer???? Name
??????????? cmprName = String(255, 0)
??????????? len5 = 256
??????????? aa = GetComputerName(cmprName, len5)
??????????? cmprName = Left(cmprName, InStr(1, cmprName, Chr(0)) - 1)
??????????? Computer = cmprName?????????????????????? '取得CPU端口号
??????????? Set CPUs = GetObject("winmgmts:{impersonationLevel=impersonate}!\" & Computer & "\root\cimv2").ExecQuery("select???? *???? from???? Win32_Processor")
??????????? For Each MyCpu In CPUs
??????????????????? SerialNo = MyCpu.ProcessorId
??????????????????? Exit For
??????????? Next
??????????? GetCPUid = SerialNo
??????????? Exit Function
doError:
??????????? GetCPUid = ""
????? End Function
保存后编译为getCPU.dll 并复制到Windows/System32下。
(三)将dll导入为com组件
运行命令:regsvr32 C:\windows\system32\getCPU.dll 显示成功导入。
(四)建立测试Java文件,内容如下:
package test;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.*;
public class CallDll {
public static void main(String args[]) {
??? ActiveXComponent app = new ActiveXComponent("getCPU.Class1");
??? Dispatch mycom = (Dispatch) app.getObject();
??? if(mycom!=null){
???? Variant result = Dispatch.callN(mycom, "GetCPUid", new String[]{""});
???? System.out.print(result);
??? }
}
}
?
?
来自:http://luohonghong.blog.163.com/blog/static/783120582009517253324/