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, "<init>", "([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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值