JNI 大小寫轉換 — 字符串數據傳遞(二)

  • D_string.java 文件
package com.ldq.d_string;

public class D_string {
	static {
		System.loadLibrary("Case");
	}

	public native String getCase(String string);

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		D_string d = new D_string();
		String s = "heLLo";
		System.out.println("before change: " + s);
		System.out.println("after change: " + d.getCase(s));
	}

}

 

  • javah -jni com.ldq.d_string.D_string 生成文件 com_ldq_d_string_D_string.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_ldq_d_string_D_string */

#ifndef _Included_com_ldq_d_string_D_string
#define _Included_com_ldq_d_string_D_string
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_ldq_d_string_D_string
 * Method:    getCase
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_ldq_d_1string_D_1string_getCase
  (JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif

 

  • 編寫源代碼文件 Case.cpp
#include <string.h>
#include "com_ldq_d_string_D_string.h"

JNIEXPORT jstring JNICALL Java_com_ldq_d_1string_D_1string_getCase (JNIEnv *env, jobject obj, jstring string)
{
	const char *s=env->GetStringUTFChars(string,0);
	char s1[16],s2[16];
	strcpy(s1,s);
	strcpy(s2,s);
	strupr(s1);
	strlwr(s2);
	strcat(s1,"_");
	strcat(s1,s2);
	env->ReleaseStringUTFChars(string,s);
	return env->NewStringUTF(s1);
}

 

  • cl /LD Case.cpp 編譯生成 Case.dll 文件
  • 拷貝 Case.dll 文件到工程目錄,運行 Java 程序 
運行結果
before change: heLLo
after change: HELLO_hello

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章