Pass a string to/from Java to/from CTag(s): JNI


To Java from C (as seen from the previous How-to) :
#include "JavaHowTo.h" 

JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello
  (JNIEnv *env, jobject obj) {
    return  env->NewStringUTF("Hello world");
}
From Java to C : Suppose we have a Java Class
public class MyClass {
  public String sayHello(){
     return  "Hello world From Java";
  }
}
then from C, we want to call the Java sayHello() method which returns a String :
JNIEXPORT void JNICALL Java_JavaHowTo_sayHello
  (JNIEnv *env, jobject obj) {
    const char *str;
  
    jclass myclass_class =(jclass) env->NewGlobalRef 
         (env->FindClass ("MyClass"));
        
    // we need the MyClass constructor    
    jmethodID constructorID = env->GetMethodID
         (myclass_class, "", "()V");
         
    // and the sayHello() method
    jmethodID methodID = env->GetMethodID
         (myclass_class, "sayHello", "()Ljava/lang/String;");

    // instanciate a MyClass object
    jobject myclass_object =  env->NewObject
         (myclass_class, constructorID);
    
    // call the sayHello() method
    jstring s = (jstring)  env->CallObjectMethod
         (myclass_object, methodID);
    
    // convert the Java String to use it in C
    str = env->GetStringUTFChars(s, 0);
    printf("%s" , str);
    env->ReleaseStringUTFChars(s, str);  
    }
The Java JNI wrapper would be
class JavaHowTo {
  public native void sayHello();
  static {
    System.loadLibrary("javahowto"); 
  }
}
And finally, to use it
public class JNIJavaHowTo {
  public static void main(String[] args) {
    JavaHowTo jht = new JavaHowTo();
    jht.sayHello();
    }
}

blog comments powered by Disqus