Click here to Skip to main content
5,785,816 members and growing! (18,563 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++), C++/CLI, C, Windows (Windows, NT4, Win2K, WinXP, Win2003, Vista), Java, Win32, Dev, Design

Posted: 13 Jan 2008
Updated: 13 Jan 2008
Views: 8,680
Bookmarked: 14 times
Note: This is an unedited reader contribution
Announcements
Loading...



Search    
Advanced Search
Sitemap
6 votes for this Article.
Popularity: 3.11 Rating: 4.00 out of 5
0 votes, 0.0%
1
1 vote, 16.7%
2
1 vote, 16.7%
3
0 votes, 0.0%
4
4 votes, 66.7%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

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


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: Pakistan Pakistan

Other popular C / C++ Language articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralUnknown ErrormemberAnkush M Gupta5:47 18 Oct '08  
Generalundeclared identifier..memberbujal21:50 1 Jul '08  
GeneralRe: undeclared identifier..memberajalilqarshi1:22 30 Jul '08  
Generalhow can i do webservicemembernorazanita18:45 30 Jun '08  
QuestionHow can i create jvm in dll?memberMember 10897920:08 17 Jun '08  
AnswerRe: How can i create jvm in dll?memberajalilqarshi1:32 30 Jul '08  
GeneralHow aboutmemberJim Crafton4:35 14 Jan '08  
GeneralRe: How aboutmemberajalilqarshi6:48 14 Jan '08  
GeneralRe: How aboutmemberJim Crafton7:37 14 Jan '08  
GeneralRe: How aboutmemberajalilqarshi20:15 14 Jan '08  
GeneralRe: How aboutmemberJim 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
Web18 | Advertise on the Code Project