JNI 段错误创建新对象

JNI segfaults creating new object

我是 JNI(和 java)的新手,所以如果这只是一个愚蠢的错误,我提前道歉。但经过大量搜索后,我找不到解释或解决方案。

我有一个名为 Tagged<T> 的参数 Java class。 Tagged<T> 的 Java 构造函数接受一个对象 T 和一个长 ptr。 C 代码有一个值,应该用值 v 和该值的内存地址创建一个标记对象。但是,当我调用 NewObject 时出现段错误。不确定问题是泛型类型构造函数(用整数调用)、Java/C 整数类型(long vs long long vs long)之间的不匹配、愚蠢的错误,还是我没有考虑过的问题。

Java Class:

public class Tagged<T> {
    private final T value;
    private long ptr;

    private TaggedValue(T value, long ptr){
        this.value = value;
        this.ptr = ptr;
    }
}

JNI代码:

JNIEXPORT jobject JNICALL Java_package_Class_function (JNIEnv * env, jclass cls, ...){

  // Find Java class
  jclass c = (*env)->FindClass(env, "package/Tagged");
  if (c == 0) {
      printf("Find Class Failed.\n");
  }else{
      printf("Found class.\n");
  }

  // Find Tagged<T> constructor
  jmethodID constructor = (*env)->GetMethodID(env,c, "<init>", "(Ljava/lang/Object;J)V");
  if (constructor == 0) {
      printf("Find method Failed.\n");
  } else {
      printf("Found method.\n");
  }

  // Get value 
  int * valptr = LibraryCall();

  // check that constructor arguments are what we expect
  int val = (int) *valptr;
  printf("Value:  %i\n",val);
  long long addr = (long long) valptr;
  printf("Address: %p = %lld = %p\n",valptr,addr,(void *)addr);

  // Try to create Tagged object
  jobject taggedval = (*env)->NewObject(env, c, constructor, val, addr);
  printf("We never get here\n");

  return taggedval;
}

控制台输出:

Found class.
Found method.
Value:  102583
Address: 0x7fdcc2d209b0 = 140586138077616 = 0x7fdcc2d209b0
#
# A fatal error has been detected by the Java Runtime Environment: 
#
#  SIGSEGV (0xb) at pc=0x0000000109ae9bcf, pid=42140, tid=3847
#
# JRE version: Java(TM) SE Runtime Environment (8.0_66-b17) (build 1.8.0_66-b17)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.66-b17 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.dylib+0x2e9bcf]  JavaCallArguments::parameters()+0x27
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /Users/eleanor/Documents/workspace/av-java/src/hs_err_pid42140.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#
Abort trap: 6

感谢any/all帮助!

你的构造函数接受一个 jobject 和一个 long,你传递给它一个 int 和一个 long long

也许您可能打算将 int 包装成 java Integer?你也应该将 long 转换为 jlong,以防 long longjlong 不是同一类型。