通过JNI从C ++调用Java函数,该函数返回一个字符串 [英] Calling a java function from C++ via JNI that returns a string

查看:77
本文介绍了通过JNI从C ++调用Java函数,该函数返回一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何在C ++应用程序中访问Java方法

Possible Duplicate:
How to access the Java method in a C++ application

假设我有一个像这样的Java类:

Suppose I have a Java class like this :

class MyClass
{
  String value = "a string value";

  String getValue()
  {
    return value;
  }
}

我已经尝试了几个小时来实现一个JNI函数,该函数调用Java函数并返回一个字符串. 有人可以通过一个片段向我展示如何使用JNI从C ++调用"getValue"函数,以及如何从"MyClass"获取具有String变量值的jstring变量.

I've been trying for hours to implement a JNI function that calls a Java function and returns a string. Could someone show me through a snippet how to call the "getValue" function from a C++ using JNI and obtain a jstring variable with the value of String variable from "MyClass.

//C ++

jobject result;

jMethodID method_getValue = m_env->GetMethodID(native_object,"getValue","()Ljava/lang/String;");

result = m_env->CallObjectMethod(native_object, method_getValue);

推荐答案

jMethodID method_getValue = m_env->GetMethodID(native_object,"getValue","()Ljava/lang/String;");

在这里,native_object应该是MyClass的类定义对象(jclass)

here, native_object is supposed to be the class definition object (jclass) of MyClass

jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

到这里:

result = m_env->CallObjectMethod(native_object, method_getValue);

NativeType CallMethod(JNIEnv * env,jobject obj, jmethodID methodID,...);

NativeType CallMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...);

您的CallObjectMethod期望MyClass中的对象作为第一个参数,而不是jclass. http://download.oracle.com/javase /1.4.2/docs/guide/jni/spec/functions.html

Your CallObjectMethod expects as first parameter an object from MyClass, no jclass. http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html

所以这里的任何一个电话都错了...

so either one of the calls is wrong here...

可能是getMethodID ...您肯定应该在那里检查NULL.

probably the getMethodID... you should definitely check for NULL there.

欢呼

这篇关于通过JNI从C ++调用Java函数,该函数返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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