Java JNI:C ++中基本(双)数组中的错误值

时间:2014-05-13 10:43:12

标签: java c++ memory-management java-native-interface

我正在尝试从C ++代码中设置Java对象的原始双数组字段。 Java对象定义为:

public class EmitterTrack {
  public int trackNumber;
  public long lastUpdatedTime;
  public int associatedEmitterModeTrackNumber;

  public EmitterObservationStruct updatedEmitterObservation;

  public double[] emitterTypeProbabilities;

  public EmitterTrack() {
    emitterTypeProbabilities = new double[9];
    updatedEmitterObservation = new EmitterObservationStruct();
  }
}

创建新EmitterTrack对象并尝试设置double数组的C ++代码如下所示:

void sendEmitterTracksToJava(jclass javaEmitterTrackClass, JNIEnv *jniEnv, EmitterTrack emitterTrack) {
  jmethodID ctor = jniEnv->GetMethodID(javaEmitterTrackClass, "<init>", "()V");

  jobject javaEmitterTrack = jniEnv->NewObject(javaEmitterTrackClass, ctor, NULL);

  jfieldID fid = jniEnv->GetFieldID(javaEmitterTrackClass, "emitterTypeProbabilities", "[D");
  jintArray jary;
  jary = (jintArray)jniEnv->GetObjectField(javaEmitterTrack, fid);
  jint *intArray = jniEnv->GetIntArrayElements(jary, 0);

  for (j = 0; j < 9; j++) {
    intArray[j] = emitterTrack.emitterTypeProbabilities[j];
  }

  jniEnv->ReleaseIntArrayElements(jary, intArray, 0);
}

当我将Java发射器轨道对象传递回Java时,我看到的输出如下:

Emitter Track:
  emitterTypeProbabilities[0]: 2.12199579097E-313
  emitterTypeProbabilities[1]: 6.3659873739E-313
  emitterTypeProbabilities[2]: 1.06099789568E-312
  emitterTypeProbabilities[3]: 1.48539705397E-312
  emitterTypeProbabilities[4]: 3.95E-322
  emitterTypeProbabilities[5]: 0.0
  emitterTypeProbabilities[6]: 0.0
  emitterTypeProbabilities[7]: 0.0
  emitterTypeProbabilities[8]: 0.0

我有什么不对的,我只是没有看到?

1 个答案:

答案 0 :(得分:0)

罗特爵士钉了它!我愚蠢地使用jintArray并获取/释放int数组而不是double。用以下内容替换修复所有内容:

jdoubleArray jary;
jary = (jdoubleArray)jniEnv->GetObjectField(javaEmitterTrack, fid);
jdouble *doubleArray = jniEnv->GetDoubleArrayElements(jary, 0);

for (j = 0; j < 9; j++) {
  doubleArray[j] = emitterTrack.emitterTypeProbabilities[j];
}

jniEnv->ReleaseDoubleArrayElements(jary, doubleArray, 0);