有些时候,要写一些程序,在 JAVA 里面好难实现, 但如果使用其它编程语言却又比较容易时,我们不妨通过 JNI 来让不同语言的程序共同完成.
JNI 的教程, 网上 C 的比较多,Java 也提供了 javah.exe 为 C 语言的 JNI 程序生成头文件, 如果你是一个 Delphi 编程员, 能否让 JAVA 与 Delphi 程序交互呢? 答案是肯定的,今天我们就来看一下一个简单的例子.
Helloworld. 主要是来认识一下, JAVA 怎样调用 Delphi 程序的方法.
好的,我们先来创建一个类:
package alvinJNI;
class HelloWorld {
static {
System.loadLibrary("DelphiAction"); //等一下我们就用Delphi来编一个程序,编好之后生成的文件就是 DelphiAction.dll 这是一个动态链接库文件,这个类里先在静态语句块中加载它
}
public native void printText(); //声明一个 native 的本地代码程序,我们使用的是 Delphi 来编写.注意:这个方法在这里只是声明,并没有定义方法体,因为这个方法我们要用 Delphi 来实现.
public static void main(String[] args) {
//创建对象并调用里面的 native 方法.
HelloWorld hw = new HelloWorld();
hw.printText();
}
}
类写完编译后,接下来的事情就由 Delphi 来解决了
我们运行 Delphi 后新建 DLL 工程: file->new->other,然后在 new 选项卡里面选择 Dll Wizard 就创建了一个新的工程了,
我们选择一个文件夹来保存工程
在保存工程后,我们需要下载 jni.pas 加入到我们的工程中,这是国外的高手写的程序单元,它方便我们的 Delphi 程序与 JAVA 交互. 可从下面地址下载到:
http://www.blogjava.net/Files/alvin/jni_pas.zip
解压之后里面有两个文件,将其存放在工程的目录下
接下来我们编写 Delphi 代码:
library DelphiAction; //这里设置动态链接库的名称,因为我们刚才写 JAVA 类时是用 DelphiAction,所以这里了要设置为 DelphiAction
{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be depl
package debug;import java.io.*;import java.lang.Thread;class MyThread extends Thread{ public int x = 0; public void run(){ System.out.println(++x); }}class R implements Runnable{ private int x = 0; public void run(){ System.out.printl ......