无法使用JNI从C ++调用Java

时间:2012-10-01 19:01:12

标签: c++ java-native-interface cocos2d-x

我有一个cocos2d-x库的小项目。我正在尝试使用C ++来调用Java函数,但我在行中得到了一个信号11异常:

// Get Status
status = jvm->GetEnv((void **) &env, JNI_VERSION_1_6);

但我不知道为什么会这样。

在我的Java类中,Getocial.java存在这个函数:

private void tweet()
    {
        String score = "123";
        String tweetUrl = "https://twitter.com/intent/tweet?text=Hello ! I have just got " + score + " points in mygame for Android !!!!";
        Uri uri = Uri.parse(tweetUrl);
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }

此功能启动导航器发布推文。从Java调用工作正常。

在我的C ++ InterfaceJNI.h中,我有:

#ifndef __INTERFACE_JNI_H__
#define __INTERFACE_JNI_H__

#include "cocos2d.h"

class InterfaceJNI
{
public:
    static void postMessageToFB();
    static void postMessageToTweet();

protected:

};

#endif // __INTERFACE_JNI_H__

在InterfaceJNI.cpp中:

#include "InterfaceJNI.h"
#include "platform/android/jni/JniHelper.h"
#include  jni.h >
#include  android/log.h >

using namespace cocos2d;

void InterfaceJNI::postMessageToTweet()
{
    int status;
    JNIEnv *env;
    JavaVM *jvm;
    jmethodID mid;
    jclass mClass;
    bool isAttached = false;

    CCLog("Static postMessageToTweet");

    // Get Status
    status = jvm->GetEnv((void **) &env, JNI_VERSION_1_6);

    CCLog("Status: %d", status);

    if(status AttachCurrentThread(&env, NULL);
        CCLog("Status 2: %d", status);
        if(status GetStaticMethodID(mClass, "tweet", "()V");
    CCLog("mID: %d", mid);

    if (mid!=0)
        env->CallStaticVoidMethod(mClass, mid);
            //-----------------------------------------------------------
    CCLog("Finish");
    if(isAttached)
        jvm->DetachCurrentThread();

    return;
}

使用以下代码从代码的一部分调用此接口:

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    InterfaceJNI::postMessageToTweet();
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    ObjCCalls::trySendATweet();
#endif

在jvm-> GetEnv((void **)& env,JNI_VERSION_1_6)上返回空指针的情况如何; ?

1 个答案:

答案 0 :(得分:2)

看起来你的jvm变量是null或者是垃圾。我使用的Cocos2D-x版本有一个名为JniHelper的类,带有static :: getJavaVM();您可能想要使用的方法。

JavaVM* vm = JniHelper::getJavaVM();
JNIEnv* env;

vm->GetEnv((void**)&env,JNI_VERSION_1_4);  // mine uses JNI_VERSION_1_4

另外,每次使用NDK构建时,请记住“刷新”您的eclipse项目。你可能已经这样做了,但是值得一试。