NDK07_JNI读取和返回字符串

NDK开发汇总

一 定义native方法,生成.h头文件

public class Jni_Test {
	public native String chineseChars(String str);
}

ray_Jni_Test.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include "jni.h"
/* Header for class ray_Jni_Test */

#ifndef _Included_ray_Jni_Test
#define _Included_ray_Jni_Test
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     ray_Jni_Test
 * Method:    chineseChars
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_ray_Jni_1Test_chineseChars
  (JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif

二 c中实现.h定义的方法,生成dll

解析传入的中文字符串,返回一个中文字符串

#include "stdafx.h"
#include "ray_Jni_Test.h"

JNIEXPORT jobject JNICALL Java_ray_Jni_1Test_chineseChars
(JNIEnv * env, jobject jobj, jstring in) {
	jboolean iscp;
	char * c_str = (*env)->GetStringChars(env, in, &iscp);
	if (iscp == JNI_TRUE)
	{
		printf("is copy: JNI_TRUE\n");
	}
	else if (iscp == JNI_FALSE)
	{
		printf("is copy: JNI_FALSE\n");
	}

	int length = (*env)->GetStringLength(env, in);
	const jchar * jcstr = (*env)->GetStringChars(env, in, NULL);
	if (jcstr == NULL) {
		return NULL;
	}
	//jchar -> char
	char * rtn = (char *)malloc(sizeof(char) * 2 * length + 3);
	memset(rtn, 0, sizeof(char) * 2 * length + 3);
	int size = 0;
	size = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)jcstr, length, rtn, sizeof(char) * 2 * length + 3, NULL, NULL);
	if (size <= 0)
	{
		printf("size: 0 \n", rtn);
		return NULL;
	}

	printf("string: %s\n", rtn);
	
	


	char *c_str2 = "返回的中文内容";

	jclass str_cls = (*env)->FindClass(env, "java/lang/String");
	
	jmethodID jmid = (*env)->GetMethodID(env, str_cls, "", "([BLjava/lang/String;)V");
	//jstring -> jbytearray
	jbyteArray bytes = (*env)->NewByteArray(env, strlen(c_str2));
	////// 将char * 赋值到 bytes
	(*env)->SetByteArrayRegion(env, bytes, 0, strlen(c_str2), c_str2);
	jstring charsetName = (*env)->NewStringUTF(env, "GB2312");
	


	if (rtn != NULL) {
		free(rtn);
		rtn = NULL;
	}
	(*env)->ReleaseStringChars(env, in, c_str);// jvm 使用。通知jvm c_str 所指的空间可以释放了
	
	fflush(stdout);
	return (*env)->NewObject(env, str_cls, jmid, bytes, charsetName);
}

三 集成dll,调用native

public static void main(String[] args) {
		
		Jni_Test jni_Test = new Jni_Test();
		System.out.println(jni_Test.chineseChars("输入的中文字符串"));
	
	}

打印结果:
is copy: JNI_TRUE
string: 输入的中文字符串
返回的中文内容

四 Demo

lsn07_JNI获取String.zip

你可能感兴趣的:(NDK)