java jni调用两种方法之动态方式

JniDynamic.java

public class JniDynamic {

  public JniDynamic() {
    System.load("/home/yym/jniDynamic/libjniDynamic.so");
  }

  public static void main(String[] args) {
    JniDynamic jni = new JniDynamic();
    System.out.println(""+jni.test1());
    jni.test2();
  }

  public native String test1();
  public native void test2();

}

JniDynamic.cpp

#include "jni.h"
#include 
#include 
#include 
using namespace std;
#define ARRAY_LENGTH(a) (sizeof(a)/sizeof(a[0]))
jstring ctest1(JNIEnv *jniEnv, jobject jobject1) {
  return jniEnv->NewStringUTF("yym-ctest1");
}
void ctest2(JNIEnv *jniEnv, jobject jobject1) {
  string str = "yym-ctest2";
  printf("%s\n", str.c_str());
  cout<<"yym:"<GetEnv((void **) &env, JNI_VERSION_1_4);
    if (r != JNI_OK) {
        return -1;
    }
    char chars[] = "JniDynamic";
    char *className = chars;
    //获取对应Java类的class
    jclass jniClass = env->FindClass(className);
    //注册,最后一个参数为注册的方法数,需要动态修改
    r = env->RegisterNatives(jniClass, mMethods, ARRAY_LENGTH(mMethods));
    //如果小于0 则注册失败
    if (r != JNI_OK) {
        return -1;
    }
    return JNI_VERSION_1_4;
}

##编译动态库

g++ -fPIC -I /home/yym/code/jdk1.8.0_361/include -I /home/yym/code/jdk1.8.0_361/include/linux -shared -o libjniDynamic.so JniDynamic.cpp

##编译java类

javac JniDynamic.java
##执行java

java JniDynamic

##执行结果

yym@ubuntu16:~/jniDynamic$ java JniDynamic
yym-ctest1
yym-ctest2
yym:yym-ctest2

你可能感兴趣的:(java,开发语言)