JNI:GetIntArrayElements()的一些问题

duyiwuer2009 2012-05-09 12:46:18

// example-1: GetStringUTFChars()
public class Prompt
{
// native method that prints a prompt and reads a line
private native String getLine(String prompt);
public static void main(String args[])
{
Prompt p = new Prompt();
String temp = new String("Type a line: ");
String input = p.getLine(temp);
System.out.println("User typed: " + input);
System.out.println(temp);
}
static
{
System.loadLibrary("Prompt");
}
}
/*
javac Prompt.java
javah Prompt
get a file: Prompt.h
*/

#include "Prompt.h"
#include <stdio.h>
#include <string.h>
JNIEXPORT jstring JNICALL Java_Prompt_getLine (JNIEnv *env, jobject obj, jstring prompt)
{
char buf[128];
const jbyte *str;
jboolean isCp;
str = (*env)->GetStringUTFChars(env, prompt, &isCp);
if (str == NULL) {
return NULL; /* OutOfMemoryError already thrown */
}
if(isCp == JNI_TRUE)
{
strcpy(str,"12345");
}
printf("%s", str);
(*env)->ReleaseStringUTFChars(env, prompt, str);
/* We assume here that the user does not type more than
* 127 characters */
scanf("%s", buf);
return (*env)->NewStringUTF(env, buf);
}
/*
set java_inc=E:\FILES\java\jdk1.6.0_29\include
cl -I%java_inc% -I%java_inc%\win32 -LD Prompt.c -FePrompt.dll
*/
/* output
the output of running class Prompt.class:
12345jdkfjkdjfkdf
User typed: jdkfjkdjfkdf
Type a line:

the output demonstrates that String instance temp did not changed, and isCopy is JNI_TRUE
*/


// example-2: GetIntArrayElements()
public class TestJNI
{
public native void intArray(int[] ii);
public static void main(String[] args)
{
System.loadLibrary("TestJNI");
TestJNI jni = new TestJNI();
int[] ii = new int[4];
for(int i = 0; i < ii.length; i++)
{
ii[i] = i;
}
jni.intArray(ii);
for(int i = 0; i < ii.length; i++)
{
System.out.println(ii[i]);
}
}
}
/*
output:
isCopy: 1
100
101
102
103

the output shows that ii has been changed, but isCopy is JNI_TRUE
*/

#include "TestJNI.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_TestJNI_intArray(JNIEnv *env, jobject obj, jintArray intArr)
{
jboolean isCp;
int i;
jsize len = (*env)->GetArrayLength(env, intArr);
jint *arr = (*env)->GetIntArrayElements(env, intArr, &isCp);
if(isCp == JNI_TRUE)
{
printf("isCopy: JNI_TRUE\n");
}
for(i = 0; i < len; i++)
{
arr[i] = 100 + i;
}
(*env)->ReleaseIntArrayElements(env, intArr, arr, 0);
}
/*
output:
isCopy: 1
100
101
102
103

the output shows that ii has been changed, but isCopy is JNI_TRUE
*/

在example-2中,isCopy 被设置为 JNI_TRUE,表示arr 指向新分配的内存,修改arr 将不影响intArr ,但输出结果却是intArr 改变了,为什么?
在example-1中,prompt 的只还是 “Type a line:”,这是合理的
...全文
438 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧