Click here to Skip to main content
6,595,854 members and growing! (20,768 online)
Email Password   helpLost your password?
Languages » C / C++ Language » Howto     Intermediate License: The Code Project Open License (CPOL)

How to Call Java functions from C Using JNI

By ajalilqarshi

This article covers the calling Java functions from C Using JNI. It also covers passing/returning simple parameters, arrays, structure arrays in Java functions
C++ (VC6, VC7, VC7.1, VC8.0), C++/CLI, C, Windows (Win2K, WinXP, Win2003, Vista), Java, Win32, Dev, Design
Posted:13 Jan 2008
Views:18,189
Bookmarked:17 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
11 votes for this article.
Popularity: 4.06 Rating: 3.90 out of 5

1
2 votes, 18.2%
2
2 votes, 18.2%
3
1 vote, 9.1%
4
6 votes, 54.5%
5

Introduction

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

Background

Few days ago my Manager asked me to write a code in C/C++ that will use the Java classes in another project. It took me a lot of time to grab the information on how to call simple functions as well as passing/returning complex data types. I found many articles describing the C/C++ function calls in Java using JNI but a 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 the CTest.cpp. Other three Java classes are simply used in place of structures in Java. As there is no structure concept in Java so we can use classes for that purposes. This is what other three .java file contains.

HelloWorld.java contain 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. I mean where the Java classes are placed. Currently it being set to D:\Java Src\TestStruct. You can modify accordingly. You will also need to modify the JDK version information in the above code as it is mentioned 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 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 HelloWorld class. These signature you can use to obtain the Method IDs. The result of 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 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 javac command.

Compile 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 following things 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


Member
Ahmad Jalil Qarshi is a Sr. Engineer (Mediation/Service Provisioning) in ZhongXing Telecom which is China's largest listed telecommunications manufacturer and wireless solutions provider.

He is currently living alone in Islamabad (Pakistan) and enjoying the beauty of green city.
Occupation: Software Developer (Senior)
Company: ZhongXing Telecom Pakistan
Location: United Kingdom United Kingdom

Other popular C / C++ Language articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 22 of 22 (Total in Forum: 22) (Refresh)FirstPrevNext
GeneralRE: How to Call Java functions from C Using JNI Pinmemberchinmaya.mishra967:46 1 Aug '09  
GeneralRe: RE: How to Call Java functions from C Using JNI PinmemberMohammed Anees0:20 14 Aug '09  
GeneralVS 2008 Pinmemberthusithagh9:47 5 Jul '09  
GeneralMy vote of 2 Pinmemberthusithagh7:54 5 Jul '09  
Questionjvm.dll not found Pinmembergdaley18:34 9 Jun '09  
AnswerRe: jvm.dll not found Pinmembergdaley19:50 9 Jun '09  
GeneralJNI_CreateJavaVM returning -3 Pinmemberrostronix16:34 14 May '09  
GeneralUnknown Error PinmemberAnkush M Gupta5:47 18 Oct '08  
QuestionRe: Unknown Error Pinmemberjakko0071:36 24 Feb '09  
AnswerRe: Unknown Error PinmemberDamos8:44 25 Mar '09  
GeneralRe: Unknown Error PinmemberJagdish Vasani5:16 12 Jun '09  
Generalundeclared identifier.. Pinmemberbujal21:50 1 Jul '08  
GeneralRe: undeclared identifier.. Pinmemberajalilqarshi1:22 30 Jul '08  
Generalhow can i do webservice Pinmembernorazanita18:45 30 Jun '08  
QuestionHow can i create jvm in dll? PinmemberMember 10897920:08 17 Jun '08  
AnswerRe: How can i create jvm in dll? Pinmemberajalilqarshi1:32 30 Jul '08  
AnswerRe: How can i create jvm in dll? Pinmemberjakko0071:46 24 Feb '09  
GeneralHow about PinmemberJim Crafton4:35 14 Jan '08  
GeneralRe: How about Pinmemberajalilqarshi6:48 14 Jan '08  
GeneralRe: How about PinmemberJim Crafton7:37 14 Jan '08  
GeneralRe: How about Pinmemberajalilqarshi20:15 14 Jan '08  
GeneralRe: How about PinmemberJim Crafton4:08 15 Jan '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Jan 2008
Editor:
Copyright 2008 by ajalilqarshi
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project