亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Android中從C ++調用Java方法

在Android中從C ++調用Java方法

qq_遁去的一_1 2019-10-24 15:12:35
我試圖從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代碼中的返回類型。


查看完整回答
反對 回復 2019-10-24
  • 2 回答
  • 0 關注
  • 644 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號