Returns a Scala object to C ++ using JNI

vm_args.version = JNI_VERSION_1_2;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_FALSE;
jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
delete options;
if (rc != JNI_OK) {
    cin.get();
    exit(EXIT_FAILURE);
}

cout << "JVM load succeeded: Version ";
jint ver = env->GetVersion();
cout << (((int) ver >> 16) & 0x0f) << "." << ((int)ver & 0x0f) << endl;
jclass thisClass = env->FindClass("Test");
cout << thisClass << endl;


jmethodID constructor = env->GetMethodID(thisClass, "<init>", "()V");
cout << constructor << endl; 

jobject testObject = env->NewObject(thisClass, constructor);

jmethodID getExpression = env->GetMethodID(thisClass, "getExpression", "()Lscala/collection/mutable/ArrayOps;");

I am trying to call a Scala function from C ++ using JNI, return a Scala object to C ++, and then translate (manually) the returned object into a C ++ object, which I can pass to the native method.

I know that when accessing Scala from C ++ through JNI there are several errors, but I would appreciate a few pointers to how to do this.

Many thanks.

+4
source share
1 answer

A general tip is to check the generated byte code before trying to figure out the scala classes. Sometimes it scalaccan create unintuitive bulky bytecode. For example, the class class

case class CaseClass(value: Int)

- ( procyon)

public class CaseClass {

    public static CaseClass apply(int p0) {
        return:CaseClass(invokevirtual:CaseClass(CaseClass$::apply, getstatic:CaseClass$(CaseClass$::MODULE$), p0:int))
    }

    public int value() {
        return:int(getfield:int(CaseClass::value, this:CaseClass))
    }

    // the rest is omitted
}

CaseClass value

jmethodID apply = env->GetStaticMethodID(thisClass, "apply", "(I)LCaseClass;");
jobject object = env->CallStaticObjectMethod(thisClass, apply, 5);
jmethodID getValue = env->GetMethodID(thisClass, "value", "()I");
jint value = env->CallIntMethod(object, getValue);
+1

Source: https://habr.com/ru/post/1654483/


All Articles