JNI将本机unsigned char数组转换为jbytearray

时间:2013-10-31 11:39:55

标签: java android c++ arrays java-native-interface

Í有JNI函数需要返回一个jbyte数组。该数组包含带有数据的c结构的字节数据。但是当我将unsinged char数组中的数据传递给jbyte数组时,我收到错误。

C结构定义如下:

// ObjectInfo struct definition
 struct ObjectInfo {
    int ObjectXCor;
    int ObjectYCor;
    int ObjectMass;
 };

 // ObjectInfo struct definition
 struct SensorDataStruct{
    int PingData;
    int IRData;
    int ForceData;
    int CompassData;
 };

 // ObjectInfo struct definition
 union PackedSend{
    struct CommStruct{
        ObjectInfo VisionData;
        SensorDataStruct SensorData;
    } CommData;
    unsigned char bytes[28];
 }SendData;

JNI方法定义如下:

JNIEXPORT jbyteArray JNICALL Java_com_example_communicationmodule_MainActivity_Convert(
    JNIEnv *env, jobject,
    jint var1,
    jint var2,
    jint var3,
    jint var4,
    jint var5,
    jint var6,
    jint var7)
{
// Array to fill with data
jbyteArray Array;

// Init  java byte array
Array = env->NewByteArray(28);

SendData.CommData.SensorData.PingData = var1;
SendData.CommData.SensorData.IRData = var2;
SendData.CommData.SensorData.ForceData = var3;
SendData.CommData.SensorData.CompassData = var4;
SendData.CommData.VisionData.ObjectXCor = var5;
SendData.CommData.VisionData.ObjectYCor = var6;
SendData.CommData.VisionData.ObjectMass = var7;

//Put the native unsigned chars in the java byte array
for(int Index=0; Index < 28; Index++){
    Array[Index] = SendData.bytes[Index];

}


// Return java array
return Array;
}

我得到的错误是: jni / HelperFunctions.cpp:44:38:错误:'*(数组+((unsigned int)索引)中的'operator ='不匹配)= SendData.PackedSend :: bytes [Index]'

我的问题是wat是将原生unsigned char数组转换为jbyte数组的正确方法吗? Doe anyboy有什么建议吗?欢迎所有提示!

更新

转换为(jbyte)后,我收到以下错误: jni / HelperFunctions.cpp:54:46:错误:'*(Array +((unsigned int)Index)中'operator ='不匹配)=(jbyte)SendData.PackedSend :: bytes [Index]' jni / HelperFunctions.cpp:54:46:注意:候选人是: C:/android-ndk-r9/platforms/android-8/arch-arm/usr/include/jni.h:66:7:注意:_jbyteArray&amp; _jbyteArray :: operator =(const _jbyteArray&amp;)

演员代码如下:

//Put the native unsigned chars in the java byte array
for(int Index=0; Index < 28; Index++){
    Array[Index] = (jbyte) SendData.bytes[Index];
}

有人有想法或建议吗?欢迎使用!

1 个答案:

答案 0 :(得分:13)

env->SetByteArrayRegion(Array, 0, 28, (jbyte*)SendData.bytes)