您的位置:首页 > 移动开发 > Android开发

android jni中C++与java互相调用小结

2014-04-08 20:06 483 查看
android jni中C++与java互相调用小结

刚学jni 在C++与java互相调用中碰到不少困难,现在互相调用成功了,特此写文做结。

环境:android-ndk-r9c

1、java类代码:

public class FfmpegJni {
private int m_sId;
public FfmpegJni(){m_sId++;}

//natvie必须声明,用于生成C/C++代码。以下函数能成功调用动态库函数。

    public native String hello();

    

// 该函数在C++中调用不成功,因此,如果C++要调用java中类方法,我采用了一种技巧,就是采用下面的静态方法调用,参数把类对象传回来,这样就可以实现了。

// 为啥该调用无法成功希望大牛看到能给指点下,开开眼界。

    public void notification(){

    //System.out.println("Got a notification.");
Log.w("rLook", "Got a notification.");

    }

    

// 以下函数在C++中成功调用

    public static void notificationByStatic(Object obj){

    FfmpegJni jt=(FfmpegJni)obj;

    String s = String.format("Got a notification in a static method[%05d].", jt.m_sId++);
Log.w("rLook", s);

    //System.out.println("Got a notification in a static method.");

    }

}

2、CPP文件

// 调用java函数

// 调用java非静态,失败,原因未知,技巧采用下面静态调用来解决该问题

int CallNotification(JNIEnv *env, jobject &jthis)

{
jclass business_class = env->GetObjectClass(jthis);
jmethodID notification_method = env->GetMethodID(business_class, "notification", "()V");
env->CallVoidMethod(business_class, notification_method);
return 0;

}

// 调用java静态,成功!

int CallNotificationS(JNIEnv *env, jobject &jthis)

{
jclass business_class = env->GetObjectClass(jthis);
jmethodID notification_method_static = env->GetStaticMethodID(business_class, "notificationByStatic", "(Ljava/lang/Object;)V");
env->CallStaticVoidMethod(business_class, notification_method_static, jthis);
env->CallStaticVoidMethod(business_class, notification_method_static, jthis);
env->CallStaticVoidMethod(business_class, notification_method_static, jthis);
return 0;

}

// 被java调用

jstring Java_com_app_z_rlook_FfmpegJni_hello

  (JNIEnv *env, jobject jthis){
CallNotificationS(env, jthis);
//CallNotification(env, jthis);

    return env->NewStringUTF("Hello jni!");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android jni c++ java