Java calls the dynamic library functions generated by C + +

Source: Internet
Author: User

Issue background

In the previous article, the author uses the arithmetic of the super-long integers in C language, because the individual needs to use this feature in a Web project.

The idea at this point is to rewrite the implementation process by using Java to rewrite the implementation of C again.

Do not talk about the amount of work, just this rewriting process let me be daunting, the programmer's most headache is a bug can not find, and another is to repeat the work.

Solution Ideas:

A chance for me to see the hope of not repeating Labor--jni

Since there has never been an engineering experience in cross-lingual collaboration, this article will document the individual's practice process

Resolution process:

1. Importing JNI header files jni.h and jni_md.h

The word "import" is actually a containment relationship, in which the user can choose to copy two header files to the local project catalog or simply not have to do any mobile operations.

The file is located in the Include directory of the JDK installation path (in fact more than one, developers can search according to their system winows/linux).

2. Java side Writing native method

Package org.demo.jni;    Public abstract class Icalchbinteger {public       native int init_hbint ();       public native void Input_hbint (String in);       Public native String Output_hbint ();       Public native string Add_hbint (string a1,string A2);       Public native string Sub_hbint (string s1,string s2);       Public native string Mul_hbint (string m1,string m2);      Public native string Div_hbint (string d1,string D2);      Public native string Mod_hbint (string mod1,string mod2);      Public native string Powermod_hbint (String p1,string p2, string p3);  }
The names of these methods are customized, there are no restrictions on the number and type of arguments, but you must add the native keyword

(Note: The example is abstract class, this is only the author's personal habits, not necessary, while in the class can also define other non-native methods, the user discretion)

3. Use the Javah command to generate the. h header File

Conversion is performed using a defined class containing native methods, and conversion is done by the Javah command.

namely:javah-jni Org.demo.jni.ICalcHBInteger

When executed correctly, the org_demo_jni_icalchbinteger.h file is generated in the directory where the command is currently executing

The file contents are similar to the following:

   /* Class:     org_demo_jni_icalchbinteger   * Method:    output_hbint   * Signature: () ljava/lang/ String;   *  /Jniexport jstring jnicall java_org_demo_jni_icalchbinteger_output_1hbint    (jnienv *, jobject);
4. How to implement the header file definition in a custom C file

After generating the header file, is the method of the head file declaration is implemented, at this time because the C-side has completed the main method (the author uses C to achieve an extra long integer),

So just use the implemented method in your custom C file to populate

Java_org_demo_jni_icalchbinteger_output_1hbint
For example, the author customizes the HBINTEGERVM.CFile, and an already implemented Super Long integer file named hbinteger.c (its corresponding header file is HBInteger.h)

HBINTEGERVM.C content is as follows:

Jniexport jstring jnicall java_com_zsf_jni_icalchbinteger_output_1hbint (          jnienv *env, Jobject obj) {      int ret;< C2/>ret = Writehbint (&last, result);      if (ret) {          printf (                  "Error in exec func [Writehbint (&last, result.\n");      }      Return nativetojstring (env, result); }
It is necessary to note that the Writehbint method is already implemented in the Hbinteger.c file. Analogy to the user, is the completed C language method.
5. Create a dynamic library for the Java side to invoke

Because the author is using a Linux system, compiling a. So file is generated, and if it is windows, you need to build the DLL file.

Generate a dynamic library file compilation command: GCC -i/usr/lib/jvm/java-7-openjdk-i386/include -fpic-shared-o libhbintegervm.so hbintegervm.c Hbinteger.c

It is important to note that the-I (uppercase of I) parameter must have, because the jni.h header file is used, and the path is dependent on the JDK version and path installed by each system, and the author's path is the default JDK installation path

If it is an integrated environment, you need to add the path value of-I to the compiled path, because the integration tool may be different, there is no specific operation, please users to find a solution.

If all goes well, the libhbintegervm.so file is generated, be sure to start with Lib, and end with. So (Linux requirements), Windows does not have this limitation, as long as the. dll ends.

6. Add the dynamic library to the JNI path of the Java project

Because I am using eclipse, I added the native JNI path directly to the project's Build path.

(that is, the path of the directory in which the dynamic library resides, you can customize a path, copy the resulting library file to the specified path, or navigate directly to the path where the generated library file is located)

7. Use the methods in the library file

For example:

public class Testjni extends icalchbinteger{          static{           system.loadlibrary ("HBINTEGERVM");       }       /**        * @param args       *      /public static void main (string[] args) {          //TODO auto-generated method stub          Test JNI test = new Testjni ();          Test.init_hbint ();            String get;            Test.add_hbint ("12345678909876543210", "9876543210123456789");          get = Test.output_hbint ();          System.out.println ("return:" + Get);}     }

It should be stated that:

System.loadlibrary ("HBINTEGERVM");
is to load the dynamic library, where HBINTEGERVM is to remove the head and tail of the library file: Lib and. So if it is a DLL file for the Windows platform, only the end, that is, the. dll section

Also see

Test.output_hbint ();
is the native method name in the previous code


Summary:

1, JNI technology is not widely used at present, the reason is because it affects the performance of the call layer (mainly the interaction time is long)

2, in non-necessary cases (such as the author of this situation is personal for lazy), try not to use the technology, so as not to bring performance and debugging trouble.

3, in the process of use, if it involves the transfer of parameters, it is important to pay attention to the conversion of parameter types, specific conversion methods, depending on the type, the method is different.

4, in the construction of the block, especially for the building block type structure of the project, the way can be worth reference and use, and even optimization.

Java calls the dynamic library functions generated by C + +

Related Article

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.