天下

记录修行的印记

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

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







posted on 2019-12-06 10:53 天下 阅读(257) 评论(0)  编辑 收藏 引用 所属分类: C/C++Java


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2015年12月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(4)

随笔分类(378)

随笔档案(329)

链接

最新随笔

搜索

最新评论