说明
Java JNI有两种方法,一种是通过javah,获取一组带签名函数,然后实现这些函数。这种方法很常用,也是官方推荐的方法。
还有一种就是JNI_OnLoad方法
CPP代码
//
// Created by heliang
//
#include <jni.h>
extern "C"{
#include <string.h>
}
static jint JNICALL cAdd(JNIEnv *env,jobject jobj,jint x,jint y){
printf("x=%d,y=%d",x,y);
return x+y;
}
static jstring JNICALL cSayHi(JNIEnv *env,jobject jobj1,jint x,jint y)
{
printf("x=%d,y=%d",x,y);
return env->NewStringUTF("hello from csayhi");
}
static jclass myClass;
static const char * const className="com/xl/JniOnloadTest";
static const JNINativeMethod gMethods[]={
{"javaAdd","(II)I",(jint*)cAdd},
{"javaSayHi","()Ljava/lang/String;",(jstring*)cSayHi}
};
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm,void * reserved){
printf("jni on load called ");
JNIEnv *env=NULL;//注册时在JNIEnv中实现的,所以必须首先获取它
int result=-1;
//从JavaVM获取JNIEnv,一般使用1.4的版本
if(vm->GetEnv((void **)&env,JNI_VERSION_1_4)!=JNI_OK){
return -1;
}
//获取映射的java类
myClass=env->FindClass(className);
if(myClass == NULL)
{
printf("cant get class %s \n",className);
return -1;
}
if(env->RegisterNatives(myClass,gMethods,sizeof(gMethods)/sizeof(gMethods[0]))<0)
{
printf("register native method failed!\n");
return -1;
}
return JNI_VERSION_1_4;
}
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
{
printf("JNI_OnUnload");
}
Java代码
public class JniOnloadTest {
public native int javaAdd(int x, int y);
public native String javaSayHi();
static{
System.loadLibrary("jni");
}
public static void main(String[] args) {
JniOnloadTest jniOnloadTest=new JniOnloadTest();
jniOnloadTest.javaAdd(1,20);
System.out.println(jniOnloadTest.javaSayHi());
}
}
运行java
java -Djava.library.path=/librar/ -jar xxx.jar
网友评论