Java Advanced: JNI usage tips _java Programming

Source: Internet
Author: User
Tags win32
Article Source: csdn Author: normalnotebook

Summary

This article provides practical examples, procedures, and guidelines for implementing a Java local approach on a 32-bit Windows platform. The examples in this article use the Java Development Kit (JDK) version 1.4.1 created by Sun Microsystems Corporation. Native code written in C language is compiled with the Microsoft Visual C + + compiler.

  Brief introduction

Recently, because the project needs, in the Web page to achieve image conversion function, and VC in the image conversion has a unique advantage. We first use VC to encapsulate the image conversion dll, and then use Java Localization method JNI invoke the DLL for image transformation, and finally invoke the JNI generated DLL with JavaBean.

Through the last few days on the Internet to find information and their own groping, harvesting a lot, is summarized as follows, so that in the future to do this aspect of the people less detours.

  A. Java section

1. No packages:

Example one:


public class Mynative

{

Static

{

System.loadlibrary ("mynative");

}

Public native static void Helloword ();

Public native static String Ctojava ();

}

  Description

1 in a Java program, you first need to declare the library name System.loadlibrary (String libname) that is invoked in the class, and locate the library in the search path of the library. The specific operation of the locator library depends on the operating system. Under Windows, first look in the current directory, and then search the directory listed by the PATH environment variable. If the library is not found, a unsatisfiedlinkerror is thrown.

2 the DLL generated by JNI is loaded here, not the name of the other generated DLL. Here, the extension of the library name can not be written out, whether it is a DLL or so, by the system itself to judge.

3 also need to make a local declaration of the method that will be invoked, the keyword is native. And only need to declare, and not need to implement specifically. Implementation is implemented in C and will be explained later.

4 If Static is added, it indicates a static method. If not added, it is a general method. Plus and no, the resulting header file has a different parameter. It will be explained later.

 Now start compiling it:

Compile it with Javac MyNative.h to generate the corresponding class file.

With Javah mynative, the corresponding MyNative.h header file is generated. The rest is to start to the VC to complete (we use VC to achieve the corresponding C implementation section).

 2. The case of a package:

Example two:


Package com. mynative;

public class Mynative

{

Static

{

System.loadlibrary ("mynative");

}

Public native static void Helloword ();

Public native static String Ctojava ();

}

The other is the same as above, which is different when using Javac and Javah. For the case of the package must pay attention to this point, at the beginning of my program always run is not successful, the problem is here.


Javac./com/mynative/mynative.java

Javah com.myNative.MyNative

There is no need to explain the above sentence. For the following sentence, explain: The front of this class is the package name. The resulting header file is: Com.mynative.mynative.h. At the beginning, the header file I generated with Javah mynative is always MyNative.h in this case. Look up the information on the Internet, see someone else's head name hit that long, my that short. But do not know why, now everyone and I like to know why. :)。 Sometimes you also need to take the path. See the syntax of the Javah specifically.

 Two C Implementation section

The MyNative.h header file that you just generated with Javah mynative is as follows:


/* Do isn't EDIT this file-it is machine generated * *

#include <jni.h>

/* Header for class mynative * *

#ifndef _included_mynative

#define _included_mynative

#ifdef __cplusplus

extern "C" {

#endif

/*

* Class:mynative

* Method:helloword

* Signature: () V

*/

Jniexport void Jnicall Java_mynative_helloword (jnienv *, jclass);

/*

* Class:mynative

* Method:ctojava

* Signature: () ljava/lang/string;

*/

Jniexport jstring jnicall Java_mynative_ctojava (jnienv *, jclass);

#ifdef __cplusplus

}

#endif

#endif

Next, is how to achieve it. In fact, what is made with JNI is also a DLL, which is invoked by Java.

In the concrete implementation, we only care about two function prototypes:


Jniexport void Jnicall Java_mynative_helloword (jnienv *, jclass); Jniexport jstring ( JNIEnv *, Jclass);

Now let's begin the exciting first step:. Select the Win32 Dynamic-link Library in Project, then click Next and the rest defaults. If you do not take the default, there will be a DllMain () function. If you take an empty DLL project, there will be no such function. I'm here to take the empty.

Then select new->file->c++ Source file to generate an empty *.cpp file. We named him mynative. The Jniexport void Jnicall Java_mynative_helloword (jnienv *, Jclass) and Jniexport jstring-Jnicall Java_mynative_ctojava ( JNIEnv *, jclass); Copy to CPP file. Then the head file is included.

 The generated MyNative.cpp content is as follows:


#include <stdio.h>

#include "MyNative.h"

Jniexport void Jnicall Java_mynative_helloword (jnienv *env, Jclass jobject)

{

printf ("Hello word!\n");

}
Jniexport jstring jnicall java_mynative_ctojavajnienv *env, Jclass obj)

{

Jstring Jstr;

Char str[]= "hello,word!\n";

Jstr=env->newstringutf (str);

return jstr;

}

Be sure to be aware of the following before compiling.

Note: Be sure to copy several header files from the Include folder in the SDK (and header files under the Win32 folder below it) to the VC's include folder. Or in the VC tools\options\directories set, the head file to include in.

 A little explanation of the program:

1 The previous article is not said, added static and not add just a parameter difference. Is the difference between jclass, no static here is jobject. That is, Jniexport void Jnicall Java_mynative_helloword (jnienv *env, Jobject obj).

2 here Jniexport and jnicall are all JNI keywords that indicate that this function is to be invoked by JNI. And jstring is a type of communication between Java string type and local string in JNI, which we can ignore and use as string (see table I for specific). The name of the function is Java_ plus the package path of the Java program plus the number of function names (see the case of a package). parameter, we only need to care about the parameters that exist in the Java program, as for jnienv* and jclass we generally do not need to touch it.

3) Newstringutf () is a JNI function that creates a new Jstring object from an array of char types containing UTF encoded characters.

4 The above program fragment Jstr=env->newstringutf (str); is written in C + + without using the env pointer. Because the C + + version of the JNIENV function contains a direct insert member function, they are responsible for finding function pointers. For the writing of C, it should read: jstr= (*env)->newstringutf (ENV,STR); because all JNI function calls use the env pointer, which is the first parameter of any local method. The env pointer is a pointer to a function pointer table. Therefore, prefix (*env) is preceded by each JNI function access to ensure that the function pointer is indirectly referenced.

When you transfer values between the C and Java programming languages, you need to understand the correspondence between these value types in both languages. These are all in the header file jni.h, using a typedef statement to declare the cost classes on the target platform for these classes. The header file also defines constants such as: Jni_false=0 and jni_true=1; table one illustrates the correspondence between Java type and C type.

  Table one Java type and C type 

Java programming language

C Programming language

Bytes

Boolean

Jboolean

1

Byte

Jbyte

1

Char

Jchar

2

Short

Jshort

2

Int

Jint

4

Long

Jlong

8

Float

Jfloat

4

Double

Jdouble

8


You are now beginning to compile the program you are writing. Select Build->rebuild all to compile the program that is written. Click Build->build MyNative.DLL to generate the DLL file.
You can also compile with the command line CL. Refer to other books in detail.

Again (once a big headache for this thing): where the DLL is placed

1) Current directory.

2) in the path referred to by path

3 to set a path in the PATH environment variable, be aware that the path you are directing should be at the top level of the. dll file, and if you refer to. dll, you will get an error.

Let's start testing our written DLL (assuming the DLL is placed correctly).


public class MyTest

{

public static void Main (string[] args)

{

Mynative a=new mynative ();

A.helloword ();

System.out.println (A.ctojava ());

}

}

Note that Mynative.class should also be placed under the same path as Mytest.java. Now start compiling run mytest, is not output on the DOS window:


Hello word!

hello,world!

The above is a simple C program that we call through the Jni method. But in reality it is much more complicated than that. Especially when calling other DLLs through JNI, there are a lot of places to pay attention to.

Now let's start with the case that contains the package, the steps are the same as above, just a little different. Let's look at one of these functions.


Jniexport void Jnicall Java_com_mynative_mynative_helloword (jnienv *env, Jclass jobject)

{

printf ("Hello word!\n");

}

Let's look at the function name. The name of the function is Java_ plus the package path of the Java program plus the number of functions. Now this sentence should be understood.

We also write a program to test the case that contains the package. Program slightly.


Javac./com/mynative/mytest.java

Java mytest

The same content is displayed on the DOS window:).

This time, let's go here, the next lecture will tell you what JNI should be aware of when calling other DLLs, and give a concrete example. A common function that converts between Unicode encoding and ASCII encoding will also be given. If you have any questions can communicate with me: normalnotebook@126.com

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.