package com.example;
public class StringDeal {
public native static String resolveString(String str);
static{
System.loadLibrary("StringDeal");
}
public static void main(String[] args) {
System.out.println(resolveString(""));
}
}
/*
* Class: com_example_StringDeal
* Method: resolveString
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT jstring JNICALL Java_com_example_StringDeal_resolveString
(JNIEnv *env, jclass jcls, jstring jstr){
char *c_str = "我是来自c的字符串,现在要返回给java端使用";
printf("%s \n", c_str);
//查找class
jclass jclz = (*env)->FindClass(env, "java/lang/String");
if (jclz == NULL)
{
return NULL;
}
//获取构造函数
jmethodID jmid = (*env)->GetMethodID(env, jclz, "<init>", "([BLjava/lang/String;)V");
if (jmid == NULL)
{
return NULL;
}
//获取字符串长度
jsize size = strlen(c_str);
//构建一个新的jbyteArray
jbyteArray jbytes =(*env)->NewByteArray(env, size);
//将c_str的值赋给jbytes
(*env)->SetByteArrayRegion(env, jbytes, 0, size, c_str);
//构建字符编码
jstring js = (*env)->NewStringUTF(env, "GB2312");
//创建一个String对象 通过构造函数String(byte [] bytes ,String charset);
return (*env)->NewObject(env, jclz, jmid, jbytes, js);;
}