I need to store a java object inside a native class. But i have this problem:
java side:
package com.gabrik.gabos;
public class Main {
static {
System.loadLibrary("JniTest");
}
public static void main(String[] args) throws Exception {
saveCar(new Car("my car"));
System.out.println("saved");
System.out.println(getSavedCar().getName());
}
public static native void saveCar(Car car);
public static native Car getSavedCar();
public static class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
com_gabrik_gabos_Main.h:
#include <jni.h>
/* Header for class com_gabrik_gabos_Main */
#ifndef _Included_com_gabrik_gabos_Main
#define _Included_com_gabrik_gabos_Main
#ifdef __cplusplus
extern "C" {
#endif
extern jobject car;
/*
* Class: com_gabrik_gabos_Main
* Method: saveCar
* Signature: (Lcom/gabrik/gabos/Main/Car;)V
*/
JNIEXPORT void JNICALL Java_com_gabrik_gabos_Main_saveCar
(JNIEnv *, jclass, jobject);
/*
* Class: com_gabrik_gabos_Main
* Method: getSavedCar
* Signature: ()Lcom/gabrik/gabos/Main/Car;
*/
JNIEXPORT jobject JNICALL Java_com_gabrik_gabos_Main_getSavedCar
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
com_gabrik_gabos_Main.cpp:
#include "pch.h"
#include "com_gabrik_gabos_Main.h"
jobject car = nullptr;
JNIEXPORT void JNICALL Java_com_gabrik_gabos_Main_saveCar
(JNIEnv* env, jclass cls, jobject value) {
car = value;
}
JNIEXPORT jobject JNICALL Java_com_gabrik_gabos_Main_getSavedCar
(JNIEnv* env, jclass cls) {
return car;
}
logs:
saved
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000016e427709d7, pid=21724, tid=0x0000000000002930
#
# JRE version: Java(TM) SE Runtime Environment (8.0_301-b09) (build 1.8.0_301-b09)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.301-b09 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# v ~StubRoutines::atomic_cmpxchg_long
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\user\IdeaProjects\GabOS\hs_err_pid21724.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
#
Why the when i pass the Car object to the saveCar, the jobject pointing to the car stops working once the method exits? because as you saw, the next time i use the jobject which was pointing to the car, now points to $h1t. What am i doing wrong?