ASM
ASM

Reputation: 79

How to get a Java Object from JNI call (C++)?

I've been researching a bit on how to make JNI calls from C++ to Java, and so far I haven't had any issue, I managed to call almost any type of function. I say ALMOST, because right now I'm facing this situation:

In Java, I have this function:

public static Object getJObject(int id){
    Object st = null;
    switch (id){
        case 0: st = "hello"; break;
        case 1: st = "bye"; break;
        case 2: st = 1; break;
        case 3: st = 2; break;
        case 4: st = 3; break;
    }
    return st;
}

As you can see, this function returns a different type of value given the ID received as a parameter.

The problem comes when trying to get that object from C++. Here's the function that makes the JNI call:

bool check(){
    JniMethodInfo methodInfo;
    jobject jobj;

    bool b = getStaticMethodInfo(methodInfo, "org.example.act.activity", "getJObject", "()Ljava/lang/Object;");

    if (!b){
        CCLog("getJObject method not found");
        return false;
    }else{
        jobj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, 0);
        return true;
    }
}

NOTE: (Although I think it is obvious) note that the getStaticMethodInfo method sets the whole process of identifying a method in a Java class. It works with every other function that I call, except for this one.

That's the only thing that I want to do...I'm pretty sure it's something about the signature specifying the type of method it is, but maybe I'm wrong. So far I've found answered questions about getting a class object or strings, but I haven't found anything on a proper Java Object...

Upvotes: 2

Views: 3164

Answers (2)

Stephen C
Stephen C

Reputation: 718816

The signature that you are providing to getStatiticMethodInfo does not match the method. For a method that takes an int argument and returns an Object, the signature should be: (I)Ljava/lang/Object;

IIRC, the method signature syntax is described in a couple of places including:

  • the JNI specification, and
  • the JVM specification

Upvotes: 3

user207421
user207421

Reputation: 310913

Double check that you have the package and class name correct, and that the signature agrees with the output of javap -s.

But it's a terrible design.

Upvotes: 1

Related Questions