Click here to Skip to main content
Click here to Skip to main content

How to Call Java Functions from C Using JNI

By , 12 Jan 2008
 

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:

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:

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:

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

instead of:

env->FunctionName(args,..);

License

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

About the Author

ajalilqarshi
Software Developer (Senior) Assured Information Systems
United Kingdom United Kingdom
Member
Ahmad Jalil Qarshi is a Software Engineer in Assured Information Systems (a Software solution provider to Pharmaceutical industry, FDA USA and EMEA) in different technologies like .NET, Delphi 2007, XSLT/Schematron.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionCalling Java from C (Mac version)memberJuan Carlos Kuri Pinto5 Apr '13 - 10:49 
Questionunable to launch JVM..memberMember 969404429 Jan '13 - 1:58 
QuestiongETTING Error jvm.dll is missing from your computermemberMember 969404429 Jan '13 - 1:10 
GeneralMy vote of 5memberolivier gg28 Jan '13 - 4:58 
QuestionUnable to Load native librarymembergupta111saurabh15 Jan '13 - 18:37 
QuestionFindclass fails with a java file including a package in itmemberSadafule24 Apr '12 - 22:42 
QuestionJNI_CreateJavaVM fails with -1memberAnneanne124 Nov '11 - 5:33 
AnswerRe: JNI_CreateJavaVM fails with -1memberMember 839413515 Nov '11 - 2:59 
QuestionJNI_CreateJavaVM doesn't workmemberAngryCats27 Sep '11 - 20:45 
AnswerRe: JNI_CreateJavaVM doesn't workmembercarterza11 Jan '12 - 14:39 
I have the exact same problem... Using VS 2010 and Windows 7.
GeneralRe: JNI_CreateJavaVM doesn't workmemberlingjia zeng7 Dec '12 - 3:37 
AnswerRe: JNI_CreateJavaVM doesn't workmemberm2e10 Dec '12 - 13:07 
GeneralRe: JNI_CreateJavaVM doesn't workmemberMoorthy Rajendran19 Feb '13 - 18:48 
QuestionGood but need other fixesmemberMember 369901527 Sep '11 - 6:35 
GeneralMy vote of 4memberMember 369901527 Sep '11 - 6:18 
GeneralIs there a wrapper generator (like swig but the other way round)?memberEulenspiegel5 May '11 - 22:01 
GeneralA good sample but need fix a few pointsmemberMember 257456113 Apr '11 - 16:12 
GeneralRe: A good sample but need fix a few pointsmemberAngryCats28 Sep '11 - 1:25 
QuestionUnable to find the requested classmemberarnott0722 Mar '11 - 5:23 
AnswerRe: Unable to find the requested classmemberMember 257456113 Apr '11 - 16:06 
QuestionHow to debug jni code [modified]memberG Mahesh Babu31 Jan '11 - 22:04 
GeneralI can´t compile the cpp codememberrolotandil5 Oct '10 - 9:51 
GeneralMy vote of 5memberT.Balaji4 Aug '10 - 19:51 
GeneralMy vote of 5membercdk28 Jul '10 - 7:06 
GeneralMy vote of 2member-midiman-19 Apr '10 - 5:25 
GeneralRe: My vote of 2memberajalilqarshi26 Apr '10 - 23:24 
GeneralThanksmembermegatelevizor16 Apr '10 - 16:48 
GeneralThanks! Comments on getting to run under GNU/LinuxmemberLaurence Finston12 Apr '10 - 5:43 
GeneralRe: Thanks! Comments on getting to run under GNU/Linuxmemberajalilqarshi12 Apr '10 - 10:53 
GeneralRe: Thanks! Comments on getting to run under GNU/LinuxmemberLaurence Finston12 Apr '10 - 21:13 
GeneralRe: Thanks! Comments on getting to run under GNU/LinuxmemberLaurence Finston12 Apr '10 - 22:54 
GeneralRe: Thanks! Comments on getting to run under GNU/LinuxmemberLaurence Finston13 Apr '10 - 0:20 
GeneralRe: Thanks! Comments on getting to run under GNU/Linuxmemberkna261118 Aug '10 - 12:04 
GeneralRe: Thanks! Comments on getting to run under GNU/LinuxmemberLaurence Finston18 Aug '10 - 21:36 
GeneralRe: Thanks! Comments on getting to run under GNU/LinuxmemberLaurence Finston18 Aug '10 - 21:47 
GeneralThanks!memberAlex Kolesnichenko6 Mar '10 - 12:05 
QuestionJNI load error - main class not foundmemberalien_invader1 Mar '10 - 11:17 
AnswerRe: JNI load error - main class not foundmemberalien_invader26 Apr '10 - 9:27 
GeneralMy application crashes while calling JNI_CreateJavaVM functionmemberKhalid Noor21 Feb '10 - 23:06 
GeneralRe: My application crashes while calling JNI_CreateJavaVM functionmemberajalilqarshi22 Feb '10 - 2:28 
GeneralRe: My application crashes while calling JNI_CreateJavaVM functionmemberKhalid Noor23 Feb '10 - 1:15 
GeneralRe: My application crashes while calling JNI_CreateJavaVM functionmemberajalilqarshi23 Feb '10 - 2:13 
GeneralRe: My application crashes while calling JNI_CreateJavaVM function [modified]memberKhalid Noor23 Feb '10 - 19:27 
GeneralRe: My application crashes while calling JNI_CreateJavaVM functionmemberMember 41280638 Mar '11 - 0:20 
GeneralRe: My application crashes while calling JNI_CreateJavaVM functionmemberpratikmota9 May '11 - 22:55 
GeneralSOLVED: Error message: "Can't find dependent libraries" [modified]membertsjakkaa29 Jan '10 - 2:25 
Generalhelp me to sort out the error [modified]membershariqmohd26 Jan '10 - 17:06 
GeneralRe: help me to sort out the errormemberajalilqarshi27 Jan '10 - 13:09 
QuestionNot working for me ...... pls help!!!memberkumarmukt20 Jan '10 - 3:20 
GeneralRE: How to Call Java functions from C Using JNImemberchinmaya.mishra961 Aug '09 - 6:46 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 13 Jan 2008
Article Copyright 2008 by ajalilqarshi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid