JNI编程中关于二维数组编程

来源:互联网 发布:中南民族大学网络教育 编辑:程序博客网 时间:2024/05/16 18:49

</pre><div>/*该函数返回一个二维int数组</div><p></p><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"> *JNI 返回一个二维数组</span><br style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px" /><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"> *基本思想:1.构建一个一维数组对象,</span><br style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px" /><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"> *</span><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px; white-space:pre"></span><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">2.构建一个数组对象的数组</span><br style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px" /><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"> *</span><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px; white-space:pre"></span><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">3.对每一个对象的数组的每一个元素赋值(对象只能对一个元素进行Get/Set方法,不能Region)</span><br style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px" /><p><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"> */</span></p><p><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"></span><pre name="code" class="cpp">

JNIEXPORT jobjectArray JNICALL Java_ObjectArrayTest_initInt2DArray(JNIEnv *env, jclass cls, int size)  //size为二维数组的大小-->int[size][size]
{
jobjectArray result;
int i;
//1.构建一个一维数组对象
jclass intArrCls = (*env)->FindClass(env, "[I");
if (intArrCls == NULL) 
{
return NULL; /* exception thrown */
}
//2.构建一个一维数组对象的数组,size表示数组的元素个数,NULL表示初始化元素
result = (*env)->NewObjectArray(env, size, intArrCls, NULL);
if (result == NULL)
{
return NULL; /* out of memory error thrown */
}
for (i = 0; i < size; i++) 
{
jint tmp[256]; /* make sure it is large enough! */
int j;
//3.构建一个int数组
jintArray iarr = (*env)->NewIntArray(env, size);
if (iarr == NULL) 
{
return NULL; /* out of memory error thrown */
}
for (j = 0; j < size; j++) 
{
tmp[j] = i + j;
}
//4.给int数组赋值 0起始位置,size大小,tmp表示源
(*env)->SetIntArrayRegion(env, iarr, 0, size, tmp);
//5.给对象赋值,只能一个一个的赋值
(*env)->SetObjectArrayElement(env, result, i, iarr);
//6.释放局部对象引用
(*env)->DeleteLocalRef(env, iarr);
}
return result;
}


0 0
原创粉丝点击