Click here to Skip to main content
16,021,621 members
Articles / Desktop Programming / Win32

How to Call Java Functions from C Using JNI

Rate me:
Please Sign up or sign in to vote.
4.47/5 (35 votes)
12 Jan 2008CPOL3 min read 444.1K   8K   46   84
This article covers calling Java functions from C using JNI. It also covers passing/returning simple parameters, arrays, and structure arrays in Java functions.

Introduction

This article describes the methodology to use Java code in C/C++. I have not only discussed simple parameter passing and returning, but complex data structures such as structures and structure arrays to Java functions as well.

Background

A few days ago, my manager asked me to write code in C/C++ that will use Java classes in other projects. It took me a lot of time to grab some information on how to call simple functions as well as pass/return complex data types. I found many articles describing C/C++ function calls in Java using JNI, but very few discussing calling Java functions in C/C++ using JNI. At that time, I decided to write an article so that other people could get help from it.

Using the code

The CTest.cpp file contains the code that calls different functions from Java classes. Java classes that are used in this project are given here under:

  • HelloWorld.java
  • ControlDetail.java
  • WorkOrder.java
  • ReturnData.java

HelloWorld.java contains the functions that will be called from CTest.cpp. The other three Java classes are simply used in place of structures in Java. As there is no structure concept in Java, we can use classes for that purpose. That is what the other three .java files contain.

HelloWorld.java contains the following functions that will be called from C/C++ code:

Java
public static void main(String args[])
{
}

public static void TestCall(String szArg)
{
} 

public static int DisplayStruct(ControlDetail ctrlDetail)
{
} 

public static void DisplayStructArray(WorkOrder ArrWO[])
{
} 

public static Object ReturnObjFunc()
{
}

To call these functions from C/C++, first you need to load the JVM using the following function:

Java
JNIEnv* create_vm(JavaVM ** jvm) {
    
    JNIEnv *env;
    JavaVMInitArgs vm_args;

    JavaVMOption options; 
    //Path to the java source code     
    options.optionString = "-Djava.class.path=D:\\Java Src\\TestStruct"; 
    vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6
    vm_args.nOptions = 1;
    vm_args.options = &options;
    vm_args.ignoreUnrecognized = 0;
    
    int ret = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);
    if(ret < 0)
        printf("\nUnable to Launch JVM\n");       
    return env;
}

Kindly note that to use this code, you will have to modify the options.optionString variable. You will have to set the path of the Java code: where the Java classes are placed. Currently, it being set to D:\Java Src\TestStruct. You can modify it to you situation. You will also need to modify the JDK version information in the above code, as shown below:

vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6

Modify it if you have another JDK version installed.

To call a specific Java function from C, you need to do the following:

  1. Obtain the class reference using the FindClass(,,) method.
  2. Obtain the method IDs of the functions of the class that you want to call using the GetStaticMethodID and GetMethodID function calls.
  3. Call the functions using CallStaticVoidMethod, CallStaticIntMethod, and CallStaticObjectMethod.

One important thing to be noted here is specifying the function signatures while obtaining the method IDs.

To obtain the correct method signature, you can use the following Java command:

javap -s -p HelloWorld

It will display you the signature of each function in the HelloWorld class. These signatures can be used to obtain the method IDs. The result of the above command can be seen below:

D:\Java Src\TestStruct>javap -s -p HelloWorld
Compiled from "HelloWorld.java"
public class HelloWorld extends java.lang.Object{
public HelloWorld();
  Signature: ()V
public static void main(java.lang.String[]);
  Signature: ([Ljava/lang/String;)V
public static void TestCall(java.lang.String);
  Signature: (Ljava/lang/String;)V
public static int DisplayStruct(ControlNEDetail);
  Signature: (LControlNEDetail;)I
public static void DisplayStructArray(WorkOrder[]);
  Signature: ([LWorkOrder;)V
public static java.lang.Object ReturnObjFunc();
  Signature: ()Ljava/lang/Object;
}

Kindly note that while specifying the method name in the GetMethodID function, if the method is a constructor, then its method name will be <init>.

Prerequisites

Before traveling down a difficult path, it is important to understand the basic concepts and to have various frameworks and tools installed on your computer.

  1. You will need the Sun Java Developer Kit (JDK). I recommend Java 1.6.0.
  2. Any C/C++ compiler installed.

How to run

To use this code, follow the instructions below:

  • Compile the *.java files using the javac command.
  • Compile the CTest.cpp file using any C++ compiler; I used MSVC++ 6.

Converting this code to pure C from C++

The attached code is written in C++. To convert this code into pure C, you will have to modify the following in the CTest.cpp file:

Use:

C++
(*env)->FunctionName(env,args,..);

instead of:

C++
env->FunctionName(args,..);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
Ahmad Qarshi is an IT Consultant and have good expertise in different development technologies. He loves to code in .NET, JavaFX, Delphi, XSLT/Schematron. Above all very keen to learn new stuff Smile | :)

Comments and Discussions

 
GeneralGreat example Pin
CungaLunga28-Sep-15 23:44
CungaLunga28-Sep-15 23:44 
QuestionI am unable to build this project Pin
Member 116512223-May-15 8:25
Member 116512223-May-15 8:25 
QuestionPlease tell me how I can use a jar and a supporting dll in java classes which need to be called from c language Pin
Member 1103432727-Oct-14 19:32
Member 1103432727-Oct-14 19:32 
AnswerRe: Please tell me how I can use a jar and a supporting dll in java classes which need to be called from c language Pin
Member 1103432728-Oct-14 23:54
Member 1103432728-Oct-14 23:54 
GeneralMy vote of 5 Pin
eiwinyan26-Aug-14 20:04
eiwinyan26-Aug-14 20:04 
GeneralMy vote of 5 Pin
digriz.cpp14-Apr-14 0:31
digriz.cpp14-Apr-14 0:31 
QuestionJDK version Pin
Debanka_Basu29-Sep-13 23:27
Debanka_Basu29-Sep-13 23:27 
AnswerRe: JDK version Pin
eiwinyan26-Aug-14 20:08
eiwinyan26-Aug-14 20:08 
Questioncall java functions ftom a jar file Pin
kishorkumar881731-Jul-13 2:42
kishorkumar881731-Jul-13 2:42 
QuestionCalling Java from C (Mac version) Pin
Juan Carlos Kuri Pinto5-Apr-13 10:49
Juan Carlos Kuri Pinto5-Apr-13 10:49 
Questionunable to launch JVM.. Pin
Member 969404429-Jan-13 1:58
Member 969404429-Jan-13 1:58 
QuestiongETTING Error jvm.dll is missing from your computer Pin
Member 969404429-Jan-13 1:10
Member 969404429-Jan-13 1:10 
GeneralMy vote of 5 Pin
olivier gg28-Jan-13 4:58
olivier gg28-Jan-13 4:58 
QuestionUnable to Load native library Pin
gupta111saurabh15-Jan-13 18:37
gupta111saurabh15-Jan-13 18:37 
QuestionFindclass fails with a java file including a package in it Pin
Sadafule24-Apr-12 22:42
Sadafule24-Apr-12 22:42 
QuestionJNI_CreateJavaVM fails with -1 Pin
Anneanne124-Nov-11 5:33
Anneanne124-Nov-11 5:33 
AnswerRe: JNI_CreateJavaVM fails with -1 Pin
Patrick_Farren15-Nov-11 2:59
Patrick_Farren15-Nov-11 2:59 
QuestionJNI_CreateJavaVM doesn't work Pin
AngryCats27-Sep-11 20:45
AngryCats27-Sep-11 20:45 
AnswerRe: JNI_CreateJavaVM doesn't work Pin
carterza11-Jan-12 14:39
carterza11-Jan-12 14:39 
GeneralRe: JNI_CreateJavaVM doesn't work Pin
lingjia zeng7-Dec-12 3:37
lingjia zeng7-Dec-12 3:37 
AnswerRe: JNI_CreateJavaVM doesn't work Pin
m2e10-Dec-12 13:07
m2e10-Dec-12 13:07 
GeneralRe: JNI_CreateJavaVM doesn't work Pin
Moorthy Rajendran19-Feb-13 18:48
Moorthy Rajendran19-Feb-13 18:48 
QuestionGood but need other fixes Pin
Member 369901527-Sep-11 6:35
Member 369901527-Sep-11 6:35 
GeneralMy vote of 4 Pin
Member 369901527-Sep-11 6:18
Member 369901527-Sep-11 6:18 
GeneralIs there a wrapper generator (like swig but the other way round)? Pin
Eulenspiegel5-May-11 22:01
Eulenspiegel5-May-11 22:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.