Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI pass parameters to method of c++

I have a c++ file myCppTest.cpp which has method

int myFunction(int argv, char **argc) {
}

and a Java native method in myClass.java

public native int myFunction (int argv, char[][] argc);

After generate the header file using javah -jni myClass, i have the header

JNIEXPORT jint JNICALL Java_JPTokenizer_init
  (JNIEnv *, jobject, jint, jobjectArray);

In my myClass.cpp, I defined

JNIEXPORT jint JNICALL Java_JPTokenizer_init
  (JNIEnv *env, jobject obj, jint argv, jobjectArray argc) {
        //need to call int myFunction(int argv, char **argc) in myCppTest.cpp 
}

How could I pass the arguments "jint argv, jobjectArray argc" to "int argv, char **argc", thanks.

EDIT:

I THINK I MADE A MISTAKE

The Java native method in myClass.java should be
public native int init (int argv, char[][] argc);

So there is

JNIEXPORT jint JNICALL Java_myClass_init
  (JNIEnv *, jobject, jint, jobjectArray);

generated after javah. And in myClass.cpp, i have

JNIEXPORT jint JNICALL Java_myClass_init
  (JNIEnv *env, jobject obj, jint argv, jobjectArray argc) {
        //need to call int myFunction(int argv, char **argc) in myCppTest.cpp 
}

like image 206
user200340 Avatar asked Jul 11 '11 16:07

user200340


2 Answers

You can create an object of the class and invoke method just like any other C++ code.

JNIEXPORT jint JNICALL Java_JPTokenizer_init
    (JNIEnv *env, jobject obj, jint argv, jobjectArray argc) {
      myClass obj;  //create object of the class you want
      obj.myFunction((int) argv, (char *) &argc); //call the method from that object
}
like image 176
Nick Avatar answered Oct 09 '22 13:10

Nick


There is no direct mapping between Java objects and C++ primitives, so you will have to convert the arguments that are passed by the Java runtime environment, and then call your function.

Java will call Java_JPTokenizer_init -- this is where you perform your conversion and invoke your "plain old" C++ function.

To convert the array of strings, you will first need to access the array, then the individual strings.

  • For array access, see http://java.sun.com/docs/books/jni/html/objtypes.html#5279.

  • For string access, see http://java.sun.com/docs/books/jni/html/objtypes.html#4001.

like image 1
Tony the Pony Avatar answered Oct 09 '22 13:10

Tony the Pony