2

我正在尝试从 c++ 调用非静态 java 方法。

示例2.java:

public class Sample2 {
    public int intMethod(int n) {
        return n*n;
    }
}

JNITest.cpp:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <memory.h>
#include <jni_md.h>
#include <jni.h>
using namespace std;

#ifdef _WIN32
#define PATH_SEPARATOR ';'
#else
#define PATH_SEPARATOR ':'
#endif

int _tmain(int argc, _TCHAR* argv[])
{
    JavaVMOption options[3];
    static JNIEnv *env;
    JavaVM *jvm;
    JavaVMInitArgs vm_args;
    long status;
    jclass cls, stringClass;
    jmethodID mid;
    jstring jstr;
    jobjectArray args;

    jint square;

    options[0].optionString = "-Djava.class.path=D:\\Studie\\EXP\\Code\\Workspace\\JNItest\\bin"; //2APL\\build"; //Workspace\\JNItest\\bin";
    options[1].optionString = "-verbose";
    options[2].optionString = "-verbose:jni";
    memset(&vm_args, 0, sizeof(vm_args));
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = options;
    status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

    if (status != JNI_ERR)
    {
        cls = env->FindClass("Sample2");
        if(cls !=0) {
            mid = env->GetMethodID(cls, "intMethod",  "(I)I");
            if(mid !=0) {
                square = env->CallIntMethod(cls, mid, 5); //this is where it all crashes
                printf("Result of intMethod: %d\n", square);
            }
        }
        jvm->DestroyJavaVM();
        return 0;
    }
    else {
        return -1;
    }
}

程序实际上找到了方法并到达square = env->CallIntMethod(cls, mid, 5);发生访问冲突的部分。如果我将其全部更改为静态方法,它运行良好,但我还需要能够调用非静态方法......

关于我在这里做错了什么有什么想法吗?

4

1 回答 1

3

调用后FindClass,您需要通过调用创建该类的实例NewObject。为此,您首先需要获取构造函数...

jmethodID constructor = (*env)->GetMethodID(env, cls, "<init>", "void(V)");

然后创建一个对象

jobject object = (*env)->NewObject(env, cls, constructor);

然后你可以调用实例函数

square = env->CallIntMethod(cls, mid, object, 5); 
于 2013-05-19T13:46:33.613 回答