将托管的unsigned char *转换为jbyte *

时间:2014-04-10 17:16:39

标签: c# c++ java-native-interface

如何将托管的unsigned char *转换为jbyte *? 因为我是新手,所以一个片段也会有所帮助。

这是我的原生代码: -

JNIEXPORT jobject JNICALL Java_com_me_NativeCaller_processImages
    (JNIEnv *env, jclass c, jbyteArray front, jbyteArray back){
unsigned char* frontBuffer = convertJByteArrayIntoUnsignedChar(env, front);
unsigned char* backBuffer = convertJByteArrayIntoUnsignedChar(env, back);
System::Collections::Generic::List<cli::array<unsigned char>^>^ returnedValue = processImages(frontBuffer,backBuffer);
jbyte* bytes;
bytes = returnedValue[1];
bytes = returnedValue[2];
jbyteArray intermediateArray1 = env->NewByteArray(1);
env->SetByteArrayRegion(intermediateArray1,0,1,bytes);

return static_cast<jobject>(intermediateArray1);

}

此处bytes = returnedValue[1];我收到错误消息“cli :: array ^的值不能分配给jbyte类型的实体*”

c#代码返回一个byte []列表: -

public static List<byte[]> processImages(byte[] frontImage, byte[] backImage)
    {
        CallProcessFrontBackAndMICR(frontImage,backImage);

        List<Image> imagesToReturn = GetAllPages(tiffFileBuffer);//convert byte[] into two separate images
        front = imagesToReturn[0];
        back = imagesToReturn[1];

        List<byte[]> bytesToReturn = new List<byte[]>();
        bytesToReturn.Add(imageToByteArray(front));
        bytesToReturn.Add(imageToByteArray(back));

        return bytesToReturn;
    }
如果有人可以帮助我,那真的很有帮助。

1 个答案:

答案 0 :(得分:1)

要将unsigned char *格式的数据转换为Java中的jbyteArray byte[],如果我没记错的话,您应该执行以下操作:

JNIEnv *env... //usually from your method signature in the jni
unsigned char *myCharData; // by stipulation you have this somehow.
const int yourArraySize = // as per usual number of elements in the char *
jbyteArray myJByteArray = env->NewByteArray(yourArraySize);
env->SetByteArrayREgion(myJByteArray, 0, yourArraySize, (jbyte *) myCharData);

// your myJByteArray is ready to use. Don't forget to memory manage your myCharData, mind!

c-style强制转换给出了jbyte的类型定义,我们可以假设它在这个实现中是安全的。

在撰写此问题时,我并未意识到数据的来源,因此可以找到特定于Android的文档here