我试图从C ++获得一个简单的Java方法调用,而Java调用本机方法。这是Java代码:public class MainActivity extends Activity { private static String LIB_NAME = "name"; static { System.loadLibrary(LIB_NAME); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.textview); tv.setText(this.getJniString()); } public void messageMe(String text) { System.out.println(text); } public native String getJniString();}我试图messageMe在getJniString*从Java到本机的方法调用过程中从本机代码调用方法。native.cpp:#include <string.h>#include <stdio.h>#include <jni.h>jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj, jint depth ){// JavaVM *vm;// JNIEnv *env;// JavaVMInitArgs vm_args;// vm_args.version = JNI_VERSION_1_2;// vm_args.nOptions = 0;// vm_args.ignoreUnrecognized = 1;//// // Construct a VM// jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args); // Construct a String jstring jstr = env->NewStringUTF("This string comes from JNI"); // First get the class that contains the method you need to call jclass clazz = env->FindClass("the/package/MainActivity"); // Get the method that you want to call jmethodID messageMe = env->GetMethodID(clazz, "messageMe", "(Ljava/lang/String;)V"); // Call the method on the object jobject result = env->CallObjectMethod(jstr, messageMe); // Get a C-style string const char* str = env->GetStringUTFChars((jstring) result, NULL); printf("%s\n", str); // Clean up env->ReleaseStringUTFChars(jstr, str);// // Shutdown the VM.// vm->DestroyJavaVM(); return env->NewStringUTF("Hello from JNI!");}
2 回答
至尊宝的传说
TA贡献1789条经验 获得超10个赞
如果是对象方法,则需要将该对象传递给CallObjectMethod:
jobject result = env->CallObjectMethod(obj, messageMe, jstr);
您正在做什么相当于jstr.messageMe()。
由于您的方法无效,因此您应该调用:
env->CallVoidMethod(obj, messageMe, jstr);
如果要返回结果,则需要更改JNI签名(()V表示void返回类型的方法)以及Java代码中的返回类型。
添加回答
举报
0/150
提交
取消