通过JNI传递Java的一个byte []一个函数在C:如何使用jarraybyte [英] Passing a byte[] in Java to a function in C through JNI: how to use jarraybyte

查看:731
本文介绍了通过JNI传递Java的一个byte []一个函数在C:如何使用jarraybyte的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次使用JNI,也是第一次,我必须写一些线以下。

This is the first time that I use the JNI and also the first time that I have to write some lines in C.

我所试图做的是非常简单的。我只是想转用C例程一个byte []的字节序。

What I am trying to do is very simple. I'm just trying to switch the endiannes of a byte[] using a C routine.

在Java的是这样做的:

In java it is done like this:

public void switchEndianness(byte[] array){

        byte byte1;
        byte byte2;

        for(int i = 0; i < array.length ; i+=2){
            byte1 = array[i];
            byte2 = array[i+1];

            array[i] = byte2;
            array[i+1] = byte1;
        }
}

因此​​,要做到这一点使用JNI,我试图imlpement同一程序中JNICALL,但它并没有编译。我到目前为止已经写的是这样的:

So to do this using JNI, I've tried to imlpement the same routine in the JNICALL, but it doesn't compile. What I've written so far is this:

JNIEXPORT void JNICALL Java_CEndianness_switchEndianness(JNIEnv *env, jobject obj, jbyteArray array, jint offset, jint length){

    char byte1;
    char byte2;

    int i;
    for(i = offset; i  < length ; i+=2){
        byte1 = array[i];
        byte2 = array[i+1];

        array[i] = byte2;
        array[i+1] = byte1;
    }
}

我不知道如何使用jbyteArray类型的数据。是它可以存储在一个字符一个jbyte ???另一个问题是..当该程序已经结束...将在Java的字节[]进行修改?抑或是只有C调用内部修改?

I have no clue how to use the jbyteArray type of data. is it possible to store a jbyte in a char??? Another question is.. when this routine is over...will the byte[] in java be modified?? Or is it only modified inside the C call?

任何帮助???

感谢大家!

推荐答案

您可以得到jbyte *由GetByteArrayElements:

you can get jbyte* by GetByteArrayElements:

jbyte* bufferPtr = (*env)->GetByteArrayElements(env, array, NULL);

和知道你的数组的长度是很重要的:

And it is important to know the length of your array:

jsize lengthOfArray = (*env)->GetArrayLength(env, array);

有jbyte *和长度,你可以做所有的事情在C-阵列。最后,释放它:

Having jbyte* and length, you can do all the things in c-array. Finally, releasing it:

(*env)->ReleaseByteArrayElements(env, array, bufferPtr, 0);

这篇关于通过JNI传递Java的一个byte []一个函数在C:如何使用jarraybyte的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆