近期提供给JAVA应用使用的编解码协议库,需求就是编码的字符串,需要解码为Java对象;回应消息的Java对象,需要编码为指定格式的字符串,把模板代码总结下,主要涉及几个点:
1、在JNI层找到Java对象,及其属性变量的值,然后转换为JNI层的内存数据;
2、在JNI层实例化Java对象,并设置这个Java对象的属性变量,并返回这个Java对象;
示例代码如下:
Java对象
代码语言:javascript复制public class TestKey {
public String name;
public String desc;
public int usage;
public String keySpec;
public String expire;
public String source;
public String credential_username;
public String credential_password;
}
JNI层实例化TestKey:
代码语言:javascript复制static jobject get_jobject(JNIEnv *env, const char *object_name){
if (env == NULL || object_name == NULL){
return NULL;
}
jclass clazz = NULL;
jobject jobj = NULL;
jmethodID mid_construct = NULL;
//1. 获取Person类的Class引用
clazz = env->FindClass(object_name);
if(clazz == NULL){
LOGD("clazz null");
return NULL;
}
//2. 获取类的默认构造函数ID
mid_construct = env->GetMethodID(clazz, "<init>", "()V");
if(mid_construct == NULL){
LOGD("construct null");
return NULL;
}
//3.实例化这个对象
jobj = env->NewObject(clazz, mid_construct);
if(jobj == NULL){
LOGD("jobject null");
return NULL;
}
return jobj;
}
JNIEXPORT jobject JNICALL Java_com_xxx_kmip_ProtocolUtil_decodeTestKeyRequestMessage
(JNIEnv *env, jclass obj, jbyteArray j_input){
jclass clazz = NULL;
jobject jobj = NULL;
jfieldID fid_name = NULL;
jfieldID fid_desc = NULL;
jfieldID fid_usage = NULL;
jfieldID fid_keySpec = NULL;
jfieldID fid_expire = NULL;
jfieldID fid_source = NULL;
jfieldID fid_credential_name = NULL;
jfieldID fid_credential_passwd = NULL;
env->GetJavaVM(&javaVM);
char* decode_str = (char*)env->GetByteArrayElements(j_input, 0);
int length = env->GetArrayLength(j_input);
char name[32] = {'