Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a C++ function from Java

I am working on a project(in Java) in which I need to evaluate user codes which may be written in C++ or Java. To evaluate a code, I need to pass a parameter to the code and get the return value from it. I can easily do it for Java codes; just create an object for the user's class and then call the function using the object. I have problems doing it for C++.

What are the possible methods I can call a C++ function from Java and get its return value? My code looks something like this (I cannot give exact code here).
C++ code

#include<stdio>
int[] function(int a[]) { } // A Simple function that takes 
                            //an array and reverses it and returns it`

Java Code from where the above function is called

int a[]; //The array I will pass
int rev[] = Somehow call C++ code from here and pass array a to it.

I read it internet that JNI can be used, but it DOES NOT allow me to use the existing code, it asks to change the int arrays to jint. Is there any way I can achieve my purpose? I just want to pass an array to an existing C++ code and get its return value.

like image 814
user3215014 Avatar asked Nov 20 '25 03:11

user3215014


1 Answers

Utilizing JNI will accomplish your task: http://docs.oracle.com/javase/6/docs/technotes/guides/jni/

Java code:

package test;

public class PerformWork 
{
public PerformWork()
{

}

public native int[] utilizeArray( int[] arr);

public int[] performWork(int[] arr)
{
    int[] results = utilizeArray(arr);
    return results;
}
}

After compiling, utilize javah to create your native header file

javah -classpath <location_of_classes> test.PerformWork

test_PerformWork.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class test_PerformWork */

#ifndef _Included_test_PerformWork
#define _Included_test_PerformWork
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     test_PerformWork
 * Method:    utilizeArray
 * Signature: ([I)[I
 */
JNIEXPORT jintArray JNICALL Java_test_PerformWork_utilizeArray
  (JNIEnv *, jobject, jintArray);

#ifdef __cplusplus
}
#endif
#endif

Lastly, implement the native function

#include "test_PerformWork.h"

JNIEXPORT jintArray JNICALL Java_test_PerformWork_utilizeArray(JNIEnv *env, jobject instance, jintArray arr)
{
jboolean isCopy = FALSE;
jsize lengthOfArr = env->GetArrayLength(arr);
jint * arrPtr = env->GetIntArrayElements(arr, &isCopy);

//call your built in function
int result[] = {1,2,3,4};
const jint * resultPtr = (const jint *)result;
jintArray javaResult = env->NewIntArray(lengthOfArr);
env->SetIntArrayRegion(javaResult, 0, lengthOfArr, resultPtr);

return javaResult;
}
like image 102
Samhain Avatar answered Nov 22 '25 15:11

Samhain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!