Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a java function from C++ via JNI that returns a string [duplicate]

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

Suppose I have a Java class like this :

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

  String getValue()
  {
    return value;
  }
}

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);
like image 450
klaus johan Avatar asked Dec 05 '10 15:12

klaus johan


1 Answers

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

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);

whereas to here:

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

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

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...

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

cheers,

like image 91
Naytzyrhc Avatar answered Oct 23 '22 23:10

Naytzyrhc