Android中C ++与Java之间的通信 [英] Communication between C++ and Java in android

查看:130
本文介绍了Android中C ++与Java之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Android中的本机代码中的C ++文件调用Java方法.我知道,我们可以通过JNI来实现这一点,但是在那种情况下,我需要从Java发起调用,这将不符合我的要求.

I want to call a java method from C++ file in native code in Android. I know, we can achieve this from JNI but in that case the, I need to initiate the call from Java, which will not fit in my requirements.

我需要从C ++中的main()函数调用用Java编写的方法.

I need to call a method written in Java from main() function in C++.

那么没有JNI,还有其他方法可以实现这一目标吗?

So is there any other approach to achieve this without JNI?

如果我可以使用JNI精确地做到这一点,请告诉我怎么做?

If I can achieve exact this thing using JNI, please let me know how?

谢谢.

谢谢, 毛利克

推荐答案

您是否检查了此内容:
https://developer.android.com/ndk/samples/sample_hellojni.html 我基本上是从那里学到的. 或:
1. https://github.com/sureshjoshi/android-ndk-swig-example .
2. https://github.com/googlesamples/android-ndk .
一个简单的搜索将带您到所有这些地方.
编辑 现在,一旦完成此操作,并且效果很好,接下来您就可以从C/C ++进行调用:
在Android中从c ++调用Java方法.这 可以帮助您的代码段是:

Did you check this:
https://developer.android.com/ndk/samples/sample_hellojni.html I basically learned from there. Or:
1. https://github.com/sureshjoshi/android-ndk-swig-example.
2. https://github.com/googlesamples/android-ndk.
A simple search would have gotten you in all these places.
EDIT Now, once you are done with this and it works well next you call from C/C++:
Calling a java method from c++ in Android. The Snippet that should help you is:

#include <string.h>
#include <jni.h>
//other imports

jstring get_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "MainActivity class");
    jclass clazz = (*env)->FindClass(env, "com/org/android/ui/activities/MainActivity");
    jmethodID mCurrentActivityId = (*env)->GetMethodID(env, clazz, "getCurrentActivityName", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, mCurrentActivityId, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

这篇关于Android中C ++与Java之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆