一款好用的JNI插件
如果你还在写jni头大,如果你还在纠结Java的变量类型和自定义类与C++的数据类型和自定义结构体的相互调用纠结,那么我推荐使用JniHelpers
项目地址:https://github.com/spotify/JniHelpers
编译一般会有很多问题
先编译一次会出错,但是会生成JniHelpers-1.0.0/src/test/cpp/TestConstants.h和JniHelpers-1.0.0/src/test/java/com/spotify/jni/TestConstants.java这两个文件
1.第一次编译命令:
$ cd JniHelpers-1.0.0
$ mkdir build;cd build
$ cmake ..
$ make
目的是编译测试文件
2.在JniHelpers-1.0.0/src/test/cpp/TestConstants.h中添加如下:
#ifndef __TestConstants_h__
#define __TestConstants_h__
/**
* Common values for tests which pass objects through JNI.
* NB: This file is GENERATED. DO NOT EDIT.
*/
#define TEST_STRING "hello, is it me you're looking for?"
#define TEST_NULL_CHAR "\0"
#define TEST_STRING_WITH_NULL_CHAR "hello \0 world"
#define TEST_UTF16_STRING u"UTF16 hello: \u2018."
#define TEST_UTF8_STRING u8"a \u0915\u093E\u091A\u0902 \u00F6 1 2 3"
#define TEST_INTEGER 42
#define TEST_SHORT 777
#define TEST_BOOLEAN true
#define TEST_FLOAT 3.14159f
#define TEST_FLOAT_TOLERANCE 0.01
#define TEST_DOUBLE 2.71828
#define TEST_BYTE 72
// #define TEST_CHAR 'ö' JAVA
#define TEST_CHAR 'a'
#endif // __TestConstants_h__
在JniHelpers-1.0.0/src/test/java/com/spotify/jni/TestConstants.java中添加修改为如下内容:
package com.spotify.jni;
/**
* Common values for tests which pass objects through JNI.
* NB: This file is GENERATED. DO NOT EDIT.
*/
public class TestConstants {
public static final String TEST_STRING = "hello, is it me you're looking for?";
public static final String TEST_NULL_CHAR = "\0";
public static final String TEST_STRING_WITH_NULL_CHAR = "hello \0 world";
public static final String TEST_UTF16_STRING = "UTF16 hello: \u2018.";
public static final String TEST_UTF8_STRING = "a \u0915\u093E\u091A\u0902 \u00F6 1 2 3";
public static final int TEST_INTEGER = 42;
public static final short TEST_SHORT = 777;
public static final boolean TEST_BOOLEAN = true;
public static final float TEST_FLOAT = 3.14159f;
public static final double TEST_FLOAT_TOLERANCE = 0.01;
public static final double TEST_DOUBLE = 2.71828;
public static final byte TEST_BYTE = 72;
public static final char TEST_CHAR = 'a';
// public static final char TEST_CHAR L'ö' CPP
}
3.在系统环境变量中设置如下环境变量:
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=$PATH:${JAVA_HOME}/bin
export JNI_LIBRARIES=${JAVA_HOME}/lib
#the include path to jni.h
export JAVA_INCLUDE_PATH=${JAVA_HOME}/include
#the include path to jni_md.h
export JAVA_INCLUDE_PATH2=${JAVA_HOME}/include/linux
export JNI_INCLUDE_DIRS=${JAVA_INCLUDE_PATH}:${JAVA_INCLUDE_PATH2}
此处我是既设置了java jdk的环境变量又设置了需要的JNI_LIBRARIES、JNI_INCLUDE_DIRS
4.重新按照第1步编译一下,可以看见编译通过和生成的静态库libJniHelpers.a
编译成功