﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>语源科技BlogJava-Java空间</title><link>http://www.blogjava.net/hanfi/</link><description>Java空间</description><language>zh-cn</language><lastBuildDate>Thu, 07 May 2026 05:51:15 GMT</lastBuildDate><pubDate>Thu, 07 May 2026 05:51:15 GMT</pubDate><ttl>60</ttl><item><title>Delphi-JNI-Java Example</title><link>http://www.blogjava.net/hanfi/archive/2009/09/29/Delphi-JNI-Java-Example.html</link><dc:creator>hanfi</dc:creator><author>hanfi</author><pubDate>Tue, 29 Sep 2009 08:18:00 GMT</pubDate><guid>http://www.blogjava.net/hanfi/archive/2009/09/29/Delphi-JNI-Java-Example.html</guid><wfw:comment>http://www.blogjava.net/hanfi/comments/296913.html</wfw:comment><comments>http://www.blogjava.net/hanfi/archive/2009/09/29/Delphi-JNI-Java-Example.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/hanfi/comments/commentRss/296913.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/hanfi/services/trackbacks/296913.html</trackback:ping><description><![CDATA[<h1>Delphi-JNI-Java Example</h1>
<br />
<strong>Downloads</strong> <br />
<a href="JNI_verB.zip">Updated JNI.pas file</a> <br />
<a href="SimpleDemo.zip">SimpleDemo.zip example</a> <br />
<a href="screenshot.zip">screenshot.zip example</a> <br />
<br />
<a href="http://www.pacifier.com/~mmead/jni/delphi/">official JNI.pas home page</a> <br />
<a href="http://www.pacifier.com/~mmead/jni/delphi/JavaToDPR/index.html">JavaToDPR tool</a> <br />
<br />
<strong>Links</strong> <br />
<a href="http://java.sun.com/j2se/1.5.0/docs/guide/jni/index.html">JNI specs</a> <br />
<a href="http://www.codeguru.com/java/JNI/index.shtml">CodeGuru JNI tips</a> <br />
<a href="http://www.turboexplorer.com/">Turbo Delphi IDE</a><br />
<p><strong>Java Native Interface</strong> is a standard programming interface for writing Java native methods. It is known to be a gray area not so many do and is perfectly fine not to develop .dll/.so libraries. After all, it's just one line away from the JVM crash if not done properly. </p>
<p>Most JNI developers use C/C++ environment, Sun releases header files only in C format. But Delphi (Object Pascal) has a very active community and JNI headers have been ported for us. <a href="http://www.pacifier.com/~mmead/jni/delphi/">Delphi JNI.pas home page</a> hosts an excellent examples and JNI.pas file.<br />
</p>
<p>Use <a href="http://www.pacifier.com/~mmead/jni/delphi/JavaToDPR/index.html">JavaToDPR</a> tool to create MyDelphi.dpr project file from .java source code. It creates all necessary function declarations from <em>native</em> tagged java functions. It simplifies .dll process to automate tedious mandatory JNI function naming convention. </p>
<p><strong>Enhanced JNI.pas</strong><br />
<a href="JNI_verB.zip">Updated JNI.pas file</a> <br />
Changes are very simple and does not modify anything from the earlier versions.
<ul>
    <li>JStringToWideString: convert jstring to widestring
    <li>WideStringToJString: convert widestring to jstring
    <li>BytesToJByteArray: convert byte array to JByteArray
    <li>IntegersToJIntArray: convert integer array to JIntArray
    <li>ThrowException: wrap native exception to java.lang.Exception
    <li>SetIntMethod: call <em>public void myClass.setInt(int id)</em> method
    <li>SetStringMethod: call <em>public void myClass.setString(String s)</em> method </li>
</ul>
Enhanced version is not found from the official JNI.pas home page. I have contacted the owner of the version to discuss whether he sees any interest to update the official version.
<p>&nbsp;</p>
<p>Java has no problems using unicode strings because the internal format is unicode already. This is not so easy in native side where you have a choice of several string types. Old legacy string is <em>ansistring</em> and unicode-aware is <em>widestring</em> variable type. If you want to send strings back and fort you should keep values in widestring variable. Knowing characters are within the range of system-default encoding you may use ansistring. But doing things right at the year +2006, you should stick to widestring variables. </p>
<p><strong>SimpleDemo example</strong><br />
<a href="SimpleDemo.zip">SimpleDemo.zip example</a> (uses enhanced JNI.pas)<br />
My goal was a short and simple Delphi study.
<ul>
    <li>unicode string interchange between Java and Delphi program
    <li>simple integer interchange between Java and Delphi program
    <li>Java class instantiation and "setter" methods from Delphi program </li>
</ul>
Final conclusion is.....it's not anything magic or too complicated.
<p>&nbsp;</p>
<p>Test program calls several native functions and print results to UTF-8 formatted html file. Web browsers have a good unicode support, so character results can be see easily. Verify <a href="SimpleDemo.png">SimpleDemo.png</a> image what you should see in SimpleDemo.html page generated by test program. </p>
<p>You need a good unicode font, some Windows has "Arial Unicode MS" which usually works fine. Its installed by some MS software (MSOffice, ...). </p>
<p>See more info in SimpleDemo.zip/readme.txt file about how to compile project. </p>
<p><strong>ScreenShot example</strong><br />
<a href="screenshot.zip">screenshot.zip example (uses enhanced JNI.pas)</a> <br />
Use native code to take a screenshot from the desktop. Code is able to "see" alphablended windows unlike Java Robot sceenshot method. Example introduces the following technique.
<ul>
    <li>return byte array from Delphi to Java
    <li>return integer array from Delphi to Java </li>
</ul>
<p>&nbsp;</p>
<p><strong>Turbo Delphi</strong><br />
<a href="http://www.turboexplorer.com/">Turbo Delphi IDE</a><br />
Turbo Delphi is a new release from Borland Delphi. Now you can get one of the best win32 development tool reasonable price....or even free of charge. Turbo Delphi Professional version provides a cutting edge version. <br />
The free Turbo Delphi Explorer edition lets beginners and hobbyists learn win32 programming. <u>But you can install only one Explorer version to the same machine</u>, so be sure to take your favourite version. This page goes for Delphi release of course. </p>
<hr />
<p><strong>SimpleDemo example: Java and Delphi code</strong><br />
Java class has one or more <em>native</em> method declarations, that are implemented in .dll library. Java program may use functions just like any other pure Java functions. <br />
<br />
You need three files in this example:<br />
SimpleDemo.java, SimpleDemo.dpr, uSimpleDemo.pas
<pre><strong>file: SimpleDemo.java</strong>
public class SimpleDemo {
public static void main(String[] args) throws Exception {
// call native Delphi method from Java
SimpleDemo sd = new SimpleDemo();
System.out.println( sd.getStringDelphiJ("Hello from Java") );
}
// declare native functions
native public String getStringDelphiJ(String s);
// load .dll library at startup
static {
System.loadLibrary("SimpleDemo");
}
}
</pre>
<br />
Native Delphi side few extra jumps to implement functions. Use JavaToDPR tool to create .dpr project file with all necessary function declarations, then implement function skeletons.
<ul>
    <li>Declare <em>library SimpleDemo;</em> to compile SimpleDemo.dll file
    <li>import <em>JNI.pas;</em> file, that implements JNI interface
    <li>declare and implement <em>native public String getStringDelphiJ(String s);</em> method
    <li>function must use a strict naming convention<br />
    <em>Java_</em> prefix is mandatory for each jni entrypoint method<br />
    <em>package_classname_</em> from java class, this example does not have a package in a .java source file, so its just classname.<br />
    <em>functionname</em> from java class<br />
    <em>PEnv: PJNIEnv; Obj:JObject</em> args are always present<br />
    <em>optional params</em> if java method declared any<br />
    </li>
</ul>
Java uses unicode for internal strings, so you should convert string function arguments and/or function return values to WideString. If you don't, use risk losing 100% international aware programming. This example uses a helper methods to convert back and fort java strings and native widestrings.
<pre><strong>file: SimpleDemo.dpr</strong>
library SimpleDemo;
// import JNI.pas file
uses
SysUtils,
uSimpleDemo in 'uSimpleDemo.pas',
JNI in '..\..\JNI\JNI.pas';
{$R *.res}
function Java_SimpleDemo_getStringDelphiJ
(PEnv: PJNIEnv; Obj: JObject; Arg1: JString): JString; stdcall;
begin
// - convert JNI-JString to Widestring (unicode)
// - call uSimpleDemo.getStringDelphiJ(s: Widestring) method
// - convert widestring to JNI-JString
// - return JNI-String back to java program
// try-catch all exceptions and wrap it to
// to java.lang.Exception
try
Result := JNI_WideStringToJString(PEnv,
uSimpleDemo.getStringDelphiJ(
JNI_JStringToWideString(PEnv, Arg1)
)
);
except
on E: Exception do begin
Result := nil;
JNI_ThrowException(PEnv, E);
end;
end;
end;
exports
// export public JNI .dll functions
Java_SimpleDemo_getStringDelphiJ;
end.
</pre>
<br />
It's a good practice to write implementations to another unit file, and keep just necessary JNI interface stuff in SimpleDemo.dpr project file.
<pre><strong>file: uSimpleDemo.pas</strong><br />
unit uSimpleDemo;
interface
// declare public functions
function getStringDelphiJ(ws: WideString): WideString; forward;
implementation
uses
SysUtils;
// implement function
function getStringDelphiJ(ws: WideString): WideString;
var
ws2: WideString;
begin
ws2 := WideUpperCase(ws);
Result := 'Uppercased in dll: ' + ws2
+ ' (len ' + IntToStr(Length(ws2)) + ')';
end;
end.
</pre>
<p>&nbsp;</p>
<hr />
<em>Last update 2006-09-12 20:40</em> 
<img src ="http://www.blogjava.net/hanfi/aggbug/296913.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/hanfi/" target="_blank">hanfi</a> 2009-09-29 16:18 <a href="http://www.blogjava.net/hanfi/archive/2009/09/29/Delphi-JNI-Java-Example.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>