IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

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

    天下发表于 2019-12-06 02:53:00
    love 0
    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();
        }
    }









    天下 2019-12-06 10:53 发表评论


沪ICP备19023445号-2号
友情链接