calling c programs from java.pdf

Upload: swaminathan-ramasubramanian

Post on 04-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Calling C Programs from Java.pdf

    1/30

    All rights reserved. Reproduction and/or distribution in whole or inpart in electronic, paper or other forms without written permission

    is prohibited.

    Java ReferencePoint SuiteSkillSoft Corporation. (c) 2002. Copying Prohibited.

    Reprinted for Balaji Nallathambi, [email protected]

    Reprinted with permission as a subscription benefit of Books24x7,http://www.books24x7.com/

    http://www.books24x7.com/http://www.books24x7.com/
  • 7/29/2019 Calling C Programs from Java.pdf

    2/30

  • 7/29/2019 Calling C Programs from Java.pdf

    3/30

    Point 5: Calling C Programs from JavaCharu SharmaThe Java Native Interface (JNI) enables you to integrate C programs and standard libraries withJava. All Java Development Kits (JDK), since the release of version 1.1, include the JNI.

    This ReferencePoint describes how to call C programs from Java using the JNI. It discusses how to

    handle primitive data types, arrays, and strings. The ReferencePoint also provides a sampleapplication in Java with native method implementation in C.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

    http://www.books24x7.com//viewer.asp?bookid=4128&chunkid=509523244?bkid=4128&destid=8375#8375
  • 7/29/2019 Calling C Programs from Java.pdf

    4/30

    An Overview of the JNIUsing the JNI, Java can interact with any existing applications or libraries written in C or C++,without the need to rewrite the existing code. In addition, you can use the JNI and libraries win C orC++ when the standard Java class library does not provide platformspecific features.

    JNI Architecture

    When a Java program is compiled, Java produces platformindependent byte code. Conversely,when a C program is compiled, it produces hostspecific code that can only be run on the type ofplatform on which it was compiled. Any program compiled in a native language depends on thenative libraries used, the operating system, and the hardware, such as the CPU instruction set.Figure 151 shows the JNI architecture:

    Figure 151: Architecture of JNIAdvantages and Disadvantages of Calling a C Program from Java

    When a C program is called from Java, it provides the following advantages:

    Eliminates the need to rewrite the functions performed by a C program in Java.

    Enables Java applications to use the standard C library.

    Enables you to include a hostspecific feature in a Java application by writing a C program,which then interacts with the Java application.

    Enables you to write in C a part of an application that has to be executed.

    The disadvantages of calling a C program from Java are:

    Develops an outcome application that is not platformindependent.

    Renders the outcome application insecure.

    Cannot integrate applets.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Calling C Programs from Java.pdf

    5/30

    Makes it difficult to debug the resultant code.

    Java ReferencePoint Suite 3

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Calling C Programs from Java.pdf

    6/30

    Tools UsedTo integrate a C program in a Java program, you can use the following tools available with the JDK:

    javah: Generates a header file that corresponds to a Java program.

    javap: Generates signatures of the native methods declared in a Java program.

    javah

    To call a C program from Java, you need to create a header file that corresponds to the Javaprogram. To achieve this, you can use the javah tool. The header file name is the same as that ofthe Java class with a .h extension added to it.

    The syntax of javah is:

    javah [options]

    You use the jni option to generate a JNI style header file.

    javap

    The javap is a class file disassembler tool available with the JDK. You can use this tool to generatethe method signatures, eliminating the chance of errors that may occur if manual signatures aregenerated.

    The syntax of javap is:

    javap [option]

    For JNI, use the following options with javap:

    s: Generates a signature.

    p: Includes the signatures of private members.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Calling C Programs from Java.pdf

    7/30

  • 7/29/2019 Calling C Programs from Java.pdf

    8/30

  • 7/29/2019 Calling C Programs from Java.pdf

    9/30

  • 7/29/2019 Calling C Programs from Java.pdf

    10/30

    {printf("This is in the C program\n");printf(".......Back to Java\n");return;

    }

    This listing shows how the methodOfC() native method is implemented. The following files areincluded in the implementation:

    jni.h: Provides the interface between Java and C.

    Demo.h: Represents the header file generated from Demo.class.

    stdio.h: Represents a standard library C header file needed for printf().

    The implementation of the method starts with the signature similar to that generated by the Demo.hheader file. You can also generate these signatures by using the javap tool. Figure 154 showshow the javap tool is used:

    Figure 154: Using javap to Generate SignaturesCompiling the Native Method and Generating the Shared Library

    The native code is implemented in Microsoft Visual C. To compile the code and build the sharedlibrary, you use the cl.exe file. This file is available at:

    C:\Program Files\Microsoft Visual Studio\VC98\bin

    Use the following command to compile the code and create the library:Cl I I LD Fe

  • 7/29/2019 Calling C Programs from Java.pdf

    11/30

  • 7/29/2019 Calling C Programs from Java.pdf

    12/30

    Using Primitive Datatypes, Arrays, and StringsDatatypes in Java and in C are not directly related. When you call C programs from Java, you needto pass arguments and accept the returned results or create Java objects in the C program. Thisrequires you to handle primitive datatypes, arrays, and strings coded in C.

    Primitive Datatypes

    To establish communication between the Java and C datatypes, you must define native equivalentsto the Java primitive datatypes, which are then used in the C code as representatives of the Javaprimitive datatypes.

    Table 151 maps the primitive datatypes and their native language equivalents:

    Table 151: Datatypes and Language Equivalents

    Java Datatype Native Language Equivalent

    Void void

    Byte jbyte

    Boolean jbooleanChar jchar

    Short jshort

    Int jint

    Long jlong

    Float jfloat

    Double jdouble

    Listing 154 shows how to access an integer variable declared in a Java program in C and modifyit:

    Listing 154: Accessing an Integer Variable of Java in C

    class JMapC{

    static int send;//Declaring the native methodprivate native void intMapjint();public static void main(String args[]){JMapC map = new JMapC();

    JMapC.send = 100;System.out.println("In Java:");System.out.println(" JMapC.send = " + JMapC.send);

    //Invoking the native methodmap.intMapjint();

    System.out.println("Back in Java:");System.out.println(" JMapC.send = " + JMapC.send);}static{

    //loading librarySystem.loadLibrary("Demo_lib");

    }}

    This listing invokes a native method that accesses an integer variable defined in the code. Theimplementation of the native method is provided by the Demo_lib library.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Calling C Programs from Java.pdf

    13/30

  • 7/29/2019 Calling C Programs from Java.pdf

    14/30

  • 7/29/2019 Calling C Programs from Java.pdf

    15/30

  • 7/29/2019 Calling C Programs from Java.pdf

    16/30

  • 7/29/2019 Calling C Programs from Java.pdf

    17/30

    {#endif/** Class: StringDemo* Method: strDemo* Signature: ()V*/

    JNIEXPORT void JNICALL Java_StringDemo_strDemo (JNIEnv *, jobject);#ifdef __cplusplus

    }

    #endif#endif

    This listing shows how to generate the header file from the StringDemo class file with the help of thejavah tool.

    Listing 1512 shows how to implement the strDemo method in C:

    Listing 1512: Implementation of the strDemo Method

    #include #include

    #include "StringDemo.h"JNIEXPORT void JNICALLJava_StringDemo_strDemo(JNIEnv *exeenv, jobject javaobj){

    jclass cls = (*exeenv)>GetObjectClass(exeenv, javaobj);jfieldID fid;jstring jstring;const char *string;printf("String accessed in C\n");fid = (*exeenv)>GetFieldID(exeenv, cls, "str", "Ljava/lang/String;");if (fid == 0){

    return;}jstring = (*exeenv)>GetObjectField(exeenv, javaobj, fid);string = (*exeenv)>GetStringUTFChars(exeenv, jstring, 0);printf("dem.s = \"%s\"\n", string);(*exeenv)>ReleaseStringUTFChars(exeenv, jstring, string);

    }

    The above listing accesses a string declared in Java code, converts it into an equivalent C stringwith the help of the GetStringUTFChars method, and then prints it.

    Figure 1510 shows the result of executing the StringDemo class file:

    Java ReferencePoint Suite 15

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Calling C Programs from Java.pdf

    18/30

  • 7/29/2019 Calling C Programs from Java.pdf

    19/30

  • 7/29/2019 Calling C Programs from Java.pdf

    20/30

  • 7/29/2019 Calling C Programs from Java.pdf

    21/30

    Note A message is also displayed when a static method from the Java program is invokedfrom the C program.

    Calling an Instance Method from a C Program

    You use the GetMethodID method to call a static method from a C program. To call an instancemethod:

    Use the GetMethodID method to obtain the instance method ID.1.

    Use the CallMethod method to pass the object reference, method ID, and thearguments when the static method is invoked.

    2.

    Listing 1516 shows how to invoke an instance method in a C program:

    Listing 1516: Invoking an Instance Method

    class DemoOfInstanceMethod{

    //Declaring native methodpublic native void callToInstanceMethod();//Instance methodpublic void instanceMethod(){System.out.println("This is an instance method");}public static void main(String args[]){DemoOfInstanceMethod dem = new DemoOfInstanceMethod();

    //Invoking the native methoddem.callToInstanceMethod();

    }static{

    //Loading the library

    System.loadLibrary("DemoOfInstanceMethod_lib");}

    }

    The above listing shows an instance method and a native method that calls the instance method.The native method is implemented using the shared library.

    Listing 1517 shows the header file that corresponds to the DemoOfInstanceMethod class file:

    Listing 1517: Header File Corresponding to the DemoOfInstanceMethod Class File

    /* DO NOT EDIT THIS FILE it is machine generated */

    #include /* Header for class DemoOfInstanceMethod */#ifndef _Included_DemoOfInstanceMethod#define _Included_DemoOfInstanceMethod#ifdef __cplusplusextern "C"{

    #endif/** Class: DemoOfInstanceMethod* Method: callToInstanceMethod* Signature: ()V*/

    JNIEXPORT void JNICALL Java_DemoOfInstanceMethod_callToInstanceMethod (JNIEnv *, jo#ifdef __cplusplus

    }

    Java ReferencePoint Suite 19

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Calling C Programs from Java.pdf

    22/30

    #endif#endif

    The above listing shows how the header file is generated from the DemoOfInstanceMethod classfile with the javah tool.

    Listing 1518 shows how to implement the callToInstanceMethod method in C:

    Listing 1518: Implementation of callToStaticMethod

    #include #include #include "DemoOfInstanceMethod.h"JNIEXPORT void JNICALLJava_DemoOfInstanceMethod_callToInstanceMethod(JNIEnv *exeenv, jobject javaobj){

    jclass cls = (*exeenv)>GetObjectClass(exeenv, javaobj);jmethodID mid = (*exeenv)>GetMethodID(exeenv, cls, "instanceMethod", "()V");if (mid == 0){

    return;}

    printf("\nCalling an instance method from C\n");//Calling an instance method from C(*exeenv)>CallVoidMethod(exeenv, javaobj, mid);

    }

    The above listing invokes an instance method from a Java program with the CallVoidMethodmethod.

    Figure 1513 shows how the DemoOfInstanceMethod class file is executed:

    Figure 1512: Executing DemoOfInstanceMethod

    Java ReferencePoint Suite 20

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

    http://www.books24x7.com//viewer.asp?bookid=4128&chunkid=509523244?bkid=4128&destid=497#497
  • 7/29/2019 Calling C Programs from Java.pdf

    23/30

    Handling Exceptions in CAn implementation of a native method in C includes the use of JNI methods, such as theCallVoidMethod. It also involves JNI pointers, such as the JNIEnv*, which access the resourcesprovided by the Java Virtual Machine (JVM).

    Exceptions occur when these methods and pointers return invalid results or no results at all. To

    handle exceptions or throw new ones from the native code, the JNI enables you to perform theseoperations in C. Listing 1519 shows how to perform exception handling in the native code:

    Listing 1519: ExceptionHandling in Native Code

    class ExceptionDemo{

    //Declaring the native methodpublic native void throwExp() throws InstantiationException;public void expHandle() throws Exception{

    //Java code throwing an exceptionthrow new Exception("This exception handling is done in Java");

    }public static void main(String args[])

    {

    ExceptionDemo dem = new ExceptionDemo();try

    {//Invoking the native method

    dem.throwExp();} catch (Exception e)

    {//Exception handling in JavaSystem.out.println("In Java:\n\t" + e);

    }}

    static{

    //Loading the librarySystem.loadLibrary("ExceptionDemo_lib");

    }

    }

    This listing declares a native method that throws the InstantiationException exception. Theexception is handled by including the invocation of the native method within a trycatch block withthe catch block showing the exception information.

    Listing 1520 shows how to generate the header file that corresponds to the ExceptionDemo classfile:

    Listing 1520: Header File for the ExceptionDemo Class File

    /* DO NOT EDIT THIS FILE it is machine generated */

    #include /* Header for class ExceptionDemo */#ifndef _Included_ExceptionDemo#define _Included_ExceptionDemo#ifdef __cplusplusextern "C"{

    #endif/** Class: ExceptionDemo* Method: throwExp* Signature: ()V*/

    JNIEXPORT void JNICALL Java_ExceptionDemo_throwExp (JNIEnv *, jobject);#ifdef __cplusplus

    }

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Calling C Programs from Java.pdf

    24/30

  • 7/29/2019 Calling C Programs from Java.pdf

    25/30

  • 7/29/2019 Calling C Programs from Java.pdf

    26/30

  • 7/29/2019 Calling C Programs from Java.pdf

    27/30

  • 7/29/2019 Calling C Programs from Java.pdf

    28/30

    Listing 1524: Implementation of Bubblesort

    #include #include #include "SampleApplication.h"JNIEXPORT void JNICALLJava_SampleApplication_sortArray(JNIEnv *exeenv, jobject javaobj, jintArray array){

    jint *buf;jint i;int x,j,k,t;int *cbuf;buf = (*exeenv)>GetIntArrayElements(exeenv, array, NULL);if (buf == NULL){

    return; /* exception occurred */}printf("\n Original contents of the array received from the Java program\n");for (i=0,j=0; i cbuf[j]){

    t=cbuf[j1];cbuf[j1]=cbuf[j];cbuf[j]=t;for(k=0;k

  • 7/29/2019 Calling C Programs from Java.pdf

    29/30

  • 7/29/2019 Calling C Programs from Java.pdf

    30/30