JNI简单示例
1、Java代码的编写
1)、首先准备一个具有本地方法的Java文件HelloJNI ,编译生成HelloJNI.class, 代码内容如下:
package com.lhy.comm;
public class HelloJNI {
static{
//加载生成的HelloJNI2.dll
System.loadLibrary("HelloJNI2");
}
public HelloJNI() {
}
//声明的本地方法
public native void sayHello(String name);
}
步骤2-生成.h头文件并实现
cmd中使用javah HelloJNI.class,生成HelloJNI.h文件,
得到JNI方法名:
JNIEXPORT void JNICALL Java_com_lhy_comm_HelloJNI (JNIEnv *, jobject, jstring name)
实现方法内容如下:
#include <jni.h>
#include <string>
JNIEXPORT void JNICALL Java_com_lhy_comm_HelloJNI (JNIEnv *, jobject, jstring name){
std::string str_name;
const char *ch;
ch = env->GetStringUTFChars(name, NULL);
str_name= ch;
env->ReleaseStringUTFChars(name, ch);
LOGE("str_name=%s\n", str_name.c_str()); }
参数类型
typedef uint8_t jboolean; /* unsigned 8 bits */
typedef int8_t jbyte; /* signed 8 bits */
typedef uint16_t jchar; /* unsigned 16 bits */
typedef int16_t jshort; /* signed 16 bits */
typedef int32_t jint; /* signed 32 bits */
typedef int64_t jlong; /* signed 64 bits */
typedef float jfloat; /* 32-bit IEEE 754 */
typedef double jdouble; /* 64-bit IEEE 754 */