Use Delphi to develop JNI applications

Source: Internet
Author: User

JNI (Java Native Interface, Java Local Interface) technology is familiar to everyone, it can help solve the limitations of Java to access the underlying hardware and improve the execution efficiency. Most of the information about JNI development is about how to develop JNI in C/C ++. Even JDK provides a javah tool to automatically generate a C language program framework. However, for a wide range of Delphi programmers, isn't it possible to use their favorite Delphi to communicate messages with Java?

Through the C program framework generated by javah and jni in JDK. analysis of the hfile, we found that the key to accessing local code using JNI in Java lies in jni. the JNINativeInterface _ structure (Struct) defined in h. If you use the Delhpi language to rewrite its definition, you can also develop local JNI code. Fortunately, there is a ready-made code on the Internet that can help you complete this complicated job, providing a jni. pas file on the http://delphi-jedi.org, that is, the jni. h, which is rewritten in Delphi language. You only need to add jni. pas to your own Delphi project to easily develop JNI Local Code Based on Delphi.

This article will use jni. pas to discuss the basic methods for developing JNI local code in Delphi.

Let's take a look at a classic HelloWorld example. Write the following Java code:

  1. ClassHelloWorld
  2. {
  3.   Public Native VoidDisplayHelloWorld ();
  4.   Static
  5. {
  6. System. LoadLibrary ("HelloWorldImpl ");
  7. }
  8. }

 

This Code declares a local method displayHelloWorld. It does not have any parameters or return values, but hopefully it will print "Hello!" on the screen! China ." . We plan to hand over this task to the local Delphi for implementation. At the same time, in the static domain of this class, use the System. loadLibrary () method to load HelloWorldImpl. dll. Note: you only need to provide the file name, but not the dll extension.

At this time, if we use the displayHelloWorld method of the HelloWorld class in our Java program, the system will throw a java. lang. UnsatisfiedLinkError error because we have not implemented local code for it.

Next we will look at the implementation of the local code in Delphi. Create a DLL project named HelloWorldImpl and enter the following code:

  1. Uses
  2. JNI;
  3. Procedure Java_HelloWorld_displayHelloWorld (PEnv: PJNIEnv; Obj: JObject); stdcall;
  4. Begin
  5. Writeln (hello! China .);
  6. End;
  7. Exports
  8. Java_HelloWorld_DisplayHelloWorld;
  9. End.

 

This code first imports the jni. pas unit. Then a process named Java_HelloWorld_displayHelloWorld is implemented. The naming of this process is exquisite. It starts with Java and connects the Java class package name, class name, and method name with an underscore. This naming method cannot be incorrect. Otherwise, the Java class cannot match the nativ method with it. At the same time, on the Win32 platform, the call method of this process can only be declared as stdcall. Although the local method declared in the HelloWorld class has no parameters, the specific process implemented in Delphi contains two parameters: PEnv: PJNIEnv and Obj: JObject. (Both types are defined in jni. pas ). The PEnv parameter represents the Jvm environment, while the Obj parameter represents the Java object that calls this process. Of course, these two parameters are not used in our simple example. Because we compile a dll file, we need to output this method in exports.

Compile the Delphi project, generate the HelloWorldImp. dll file, and place it in the directory that can be found by the system during runtime. Generally, it is under the current directory, and compile the Java class that calls the HelloWorld class as follows:

  1. ClassMainTest
  2. {
  3. Public Static VoidMain (String[] Args)
  4. {
  5. NewHelloWorld (). displayHelloWorld ();
  6. }
  7. }

 

Run it. If the console outputs "Hello! China .", Congratulations, you have successfully developed the first JNI application using Delphi.

Next, we will slightly increase the value to study the parameter transfer. Or HelloWorld. Modify the displayHelloWorld method you just wrote so that the displayed string is dynamically determined by the Java class. The Java code of the new displayHelloWorld method is as follows:

  1. Public Native VoidDisplayHelloWorld (StringStr );


Modify the Delphi code. This time, the first inherent parameter PEnv of the process is used, as shown below:

  1. Procedure Java_HelloWorld_displayHelloWorld (PEnv: PJNIEnv; Obj: JObject; str: JString); stdcall;
  2. Var
  3. JVM: TJNIEnv;
  4. Begin
  5. JVM: = TJNIEnv. Create (PEnv );
  6. Writeln (JVM. UnicodeJStringToString (str ));
  7. JVM. Free;
  8. End;

 

In the parameter table of this process, we add the str: JString parameter, which is responsible for receiving the str real parameters passed in from HelloWorld. Note the differences in implementation code. Because a parameter is used, the conversion between the data types of the parameter is involved. The Java String object passed from the Java program is now a special JString type, and JString cannot be directly used in Delphi. You need to use the UnicodeJStringToString () method provided by TJNIEnv to convert it to a string type that can be recognized by Delphi. Therefore, we need to construct the Instance Object of TJNIEnv and use its method (TJNIEnv provides many methods and only uses one of its most basic and commonly used methods). Finally, remember to release it. The steps for passing basic data type parameters from Java to Delphi and using in Delphi are as simple as that.

We will make it a little more difficult to build a custom Book class and pass its instance object as a parameter to Delphi to study how to access the public fields of object parameters in local code.

First, define a simple Java class Book. To make the problem a little more complicated, we added a java. util. Date field to the Book. The Code is as follows:

  1. Public ClassBook
  2. {
  3. Public StringTitle;// Title
  4. Public DoublePrice;// Price
  5. PublicDate pdate;// Date of purchase
  6. }
  7.  


Similarly, add a local method displayBookInfo to the HelloWorld class. The Code is as follows:

  1. Public Native VoidDisplayBookInfo (Book B );
  2. The Delphi code is a little more complex than the previous examples. Let's take a look at the code first:
  3. Procedure Java_HelloWorld_displayBookInfo (PEnv: PJNIEnv; Obj: JObject; B: JObject); stdcall;
  4. Var
  5. JVM: TJNIEnv;
  6. C, c2: JClass;
  7. Fid: JFieldID;
  8. Mid: JMethodID;
  9. Title, datestr: string;
  10. Price:Double;
  11. Pdate: JObject;
  12. Begin
  13. JVM: = TJNIEnv. Create (PEnv );
  14. C: = JVM. GetObjectClass (B );
  15. Fid: = JVM. GetFieldID (c, title, LjavalangString;);
  16. Title: = JVM. UnicodeJStringToString (JVM. GetObjectField (B, fid ));
  17. Fid: = JVM. GetFieldID (c, price, D );
  18. Price: = JVM. GetDoubleField (B, fid );
  19. Fid: = JVM. GetFieldID (c, pdate, LjavautilDate ;);
  20. Pdate: = JVM. GetObjectField (B, fid );
  21. C2: = JVM. GetObjectClass (pdate );
  22. Mid: = JVM. GetMethodID (c2, toString, () LjavalangString;);
  23. Datestr: = JVM. JStringToString (JVM. CallObjectMethodA (pdate, mid, nil ));
  24. WriteLn (Format (% s % f % s ,&

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.