How to call C code in Java-(implement the Java local method in Linux)

Source: Internet
Author: User

Original article: Java calls C (implementing Java local methods in Linux)

 

 

1. Declare local methods in the Java class and use the native keyword

 

  1. Public class mynative {
  2. Public void showparms (string S, int I, Boolean B ){
  3. Showparms0 (S, I, B );
  4. }
  5. Public int hypotenuse (int A, int B ){
  6. Return hypotenuse0 (A, B );
  7. }
  8. Public void setarray (Boolean [] BA ){
  9. For (INT I = 0; I <ba. length; I ++)
  10. Ba [I] = true;
  11. Setarray0 (BA );
  12. }
  13. Public void showstrings (string [] SA ){
  14. Showstrings0 (SA );
  15. }
  16. Public String [] getstrings (){
  17. Return getstrings0 ();
  18. }
  19. Private native void showparms0 (string S, int I, Boolean B );
  20. Private native int hypotenuse0 (int A, int B );
  21. Private native void setarray0 (Boolean [] BA );
  22. Private native void showstrings0 (string [] SA );
  23. Private native string [] getstrings0 ();
  24. Static {
  25. System. loadlibrary ("mynative ");
  26. }
  27. Public static void main (string [] ARGs ){
  28. Mynative OBJ = new mynative ();
  29. OBJ. showparms ("hello", 23, true );
  30. OBJ. showparms ("world", 34, false );
  31. System. Out. println (obj. hypotenuse (3, 4 ));
  32. System. Out. println (obj. hypotenuse (9, 12 ));
  33. Boolean [] BA = new Boolean [5];
  34. OBJ. setarray (BA );
  35. For (INT I = 0; I <ba. length; I ++)
  36. System. Out. println (BA [I]);
  37. String [] SA = new string [] {"hello,", "World! "," JNI "," is "," Fun ."};
  38. OBJ. showstrings (SA );
  39. OBJ. showstrings (obj. getstrings ());
  40. }
  41. }

 

Loadlibrary
public static void loadLibrary(String libname)
Loads the system library specified by libnameArgument. The manner in which a library name is mapped to the actual system library is system dependent.

The callSystem.loadLibrary(name)Is required tively equivalent to the call

 Runtime.getRuntime().loadLibrary(name) 
Parameters:
libname-The name of the library.
Throws:
SecurityException -If a security manager exists and its checkLinkMethod doesn' t allow loading of the specified dynamic library
UnsatisfiedLinkError -If the library does not exist.
NullPointerException -If libnameIs null
See also:
Runtime.loadLibrary(java.lang.String), SecurityManager.checkLink(java.lang.String)

Ii. Generate. Class and. H files

  1. Javac mynative. Class
  2. Javah-JNI mynative

 

The generated. h file is as follows:

 

  1. /* Do not edit this file-it is machine generated */
  2. # Include <JNI. h>
  3. /* Header for class mynative */
  4. # Ifndef _ included_mynative
  5. # DEFINE _ included_mynative
  6. # Ifdef _ cplusplus
  7. Extern "C "{
  8. # Endif
  9. /*
  10. * Class: mynative
  11. * Method: getstrings0
  12. * Signature: () [ljava/lang/string;
  13. */
  14. Jniexport jobjectarray jnicall java_mynative_getstrings0
  15. (Jnienv *, jobject );
  16. /*
  17. * Class: mynative
  18. * Method: showstrings0
  19. * Signature: ([ljava/lang/string;) V
  20. */
  21. Jniexport void jnicall java_mynative_showstrings0
  22. (Jnienv *, jobject, jobjectarray );
  23. /*
  24. * Class: mynative
  25. * Method: showparms0
  26. * Signature: (ljava/lang/string; IZ) V
  27. */
  28. Jniexport void jnicall java_mynative_showparms0
  29. (Jnienv *, jobject, jstring, jint, jboolean );
  30. /*
  31. * Class: mynative
  32. * Method: hypotenuse0
  33. * Signature: (ii) I
  34. */
  35. Jniexport jint jnicall java_mynative_hypotenuse0
  36. (Jnienv *, jobject, jint, jint );
  37. /*
  38. * Class: mynative
  39. * Method: setarray0
  40. * Signature: ([Z) V
  41. */
  42. Jniexport void jnicall java_mynative_setarray0
  43. (Jnienv *, jobject, jbooleanarray );
  44. # Ifdef _ cplusplus
  45. }
  46. # Endif
  47. # Endif

 

3. Implement the methods declared in. h file in C Language

Include the generated. h file in the header file and use the C language to implement these local methods. The Code is as follows:

 

  1. # Include <stdio. h>
  2. # Include <math. h>
  3. # Include "mynative. H"
  4. Jniexport void jnicall java_mynative_showparms0
  5. (Jnienv * ENV, jobject OBJ, jstring S, jint I, jboolean B)
  6. {
  7. Const char * szstr = (* env)-> getstringutfchars (ENV, S, 0 );
  8. Printf ("string = [% s]/n", szstr );
  9. Printf ("Int = % d/N", I );
  10. Printf ("Boolean = % s/n", (B = jni_true? "True": "false "));
  11. (* Env)-> releasestringutfchars (ENV, S, szstr );
  12. }
  13. Jniexport jint jnicall java_mynative_hypotenuse0
  14. (Jnienv * ENV, jobject OBJ, jint A, jint B)
  15. {
  16. Int RTN = (INT) SQRT (double) (A * A) + (B * B )));
  17. Return (jint) RTN;
  18. }
  19. Jniexport void jnicall java_mynative_setarray0
  20. (Jnienv * ENV, jclass CLs, jbooleanarray BA)
  21. {
  22. Jboolean * PBA = (* env)-> getbooleanarrayelements (ENV, Ba, 0 );
  23. Jsize Len = (* env)-> getarraylength (ENV, BA );
  24. Int I = 0;
  25. // Change the even array element
  26. For (I = 0; I <Len; I + = 2)
  27. PBA [I] = jni_false;
  28. (* Env)-> releasebooleanarrayelements (ENV, Ba, PBA, 0 );
  29. }
  30. Jniexport void jnicall java_mynative_showstrings0
  31. (Jnienv * ENV, jclass CLs, jobjectarray SA)
  32. {
  33. Int Len = (* env)-> getarraylength (ENV, SA );
  34. Int I = 0;
  35. For (I = 0; I <Len; I ++)
  36. {
  37. Jobject OBJ = (* env)-> getobjectarrayelement (ENV, SA, I );
  38. Jstring STR = (jstring) OBJ;
  39. Const char * szstr = (* env)-> getstringutfchars (ENV, STR, 0 );
  40. Printf ("% s", szstr );
  41. (* Env)-> releasestringutfchars (ENV, STR, szstr );
  42. }
  43. Printf ("/N ");
  44. }
  45. Jniexport jobjectarray jnicall java_mynative_getstrings0
  46. (Jnienv * ENV, jclass CLs)
  47. {
  48. Jstring STR;
  49. Jobjectarray ARGs = 0;
  50. Jsize Len = 5;
  51. Char * Sa [] = {"hello,", "World! "," JNI "," is "," fun "};
  52. Int I = 0;
  53. ARGs = (* env)-> newobjectarray (ENV, Len, (* env)-> findclass (ENV, "Java/lang/string"), 0 );
  54. For (I = 0; I <Len; I ++)
  55. {
  56. STR = (* env)-> newstringutf (ENV, sa [I]);
  57. (* Env)-> setobjectarrayelement (ENV, argS, I, STR );
  58. }
  59. Return ARGs;
  60. }

 

4. compile C language files

Write the MAKEFILE file, compile the C code you just wrote, and generate the. So file. in Linux (Windows, DLL files)

 

  1. Libmynative. So: mynative. O makefile
  2. Gcc-wall-rdynamic-shared-O libmynative. So mynative. o
  3. Mynative. O: mynative. c mynative. h
  4. Gcc-wall-C mynative. C-I./-I/sandbox/java2s/jdk1.6.0 _ 16/include-I/sandbox/java2s/jdk1.6.0 _ 16/include/Linux
  5. CL:
  6. Rm-RF *. O *. So

 

"/Sandbox/java2s/jdk1.6.0 _ 16" is the JDK installation directory.

"Libmynative. So" is in the Java class

Static {
System. loadlibrary ("mynative ");
}

Parameters + Lib in static methods

 

5. Configure Environment Variables

Modify the. bash_profile file and configure the environment variables. Because the generated. So file is in the current directory

The. bash_profile file is set as follows:

Export LD_LIBRARY_PATH = ./

 

6. Execute the target file

Run the Java mynative command. The result is as follows:

 

 

In Linux, Java local method (Java calls C) is implemented.

References:

Http://www.ibm.com/developerworks/cn/java/jnimthds/index.html

 

 

 

Java is used in combination with C and C ++, Java calls C language, Java calls C ++ language, Java JNI implementation, and Java local call method.

 

From: http://blog.csdn.net/kangkanglou/archive/2010/08/13/5807787.aspx

Author: kangkang_kevin

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.