Search code examples
cjava-native-interface

How can I assign the NULL to a float/double variable?


I have a problem using JNI.

jboolean z = (jboolean) NULL; // ok
jbyte    b = (jbyte)    NULL; // ok
jchar    c = (jchar)    NULL; // ok
jshort   s = (jshort)   NULL; // ok
jint     i = (jint)     NULL; // ok
jlong    j = (jlong)    NULL; // ok

jobject  l = (jobjec)   NULL; // ok

jfloat   f = (jlong)     NULL; // NOT OK 
jdouble  d = (jdouble)   NULL; // NOT OK

Compiler complaines

[ERROR] /....c:112:28: error: pointer cannot be cast to type 'jfloat' (aka 'float')
[ERROR]   jfloat result = (jfloat) NULL;
[ERROR]                            ^~~~
[ERROR] /usr/include/sys/_types/_null.h:29:15: note: expanded from macro 'NULL'
[ERROR] #define NULL  __DARWIN_NULL
[ERROR]               ^~~~~~~~~~~~~
[ERROR] /usr/include/sys/_types.h:52:23: note: expanded from macro '__DARWIN_NULL'
[ERROR] #define __DARWIN_NULL ((void *)0)
[ERROR]                       ^~~~~~~~~~~
[ERROR] 1 error generated.

How can I fix this?


I'm writing methods for each of those values.

jboolean doSome() {
    jboolean result = (jboolean) NULL;
    /*
     * at here result may be initialized or remain as NULL
     */
    return result;
}

I intended to write a function combines following three methods.

(*env)->GetObjecClass(JNIEnv *, jobject);
(*env)->GetMethodID(JNIEnv *, jclass, char *, char *);
(*env)->CallBooleanMethodA(JNIEnv *, jclass, jmethodID, jvalue *);

like this.

jboolean CallBooleanMethodAMmMs(JNIEnv * env, jobject obj, char * mname,
                                char * msig, jvalue * args) {
  jboolean result = (jboolean) NULL;
  jclass clazz = (*env)->GetObjectClass(env, obj);
  jmethodID methodID = (*env)->GetMethodID(env, clazz, mname, msig);
  if (methodID != NULL) {
    result = (*env)->CallBooleanMethodA(env, obj, methodID, args);
  }
  (*env)->DeleteLocalRef(env, clazz);
  return result;
}

I thought I can use NULL for the case of any unsuccessful situation such as methodID == NULL.

I think I should use a jobject instead of primitives, right?


Solution

  • You cannot (and should not) assign a pointer to a normal variable.

    I really don't know why it allowed for some other normal data types, as you have mentioned. Compiler should have produced same warning equally for all assignment from pointer to other non-pointer data type

    NULL is a void pointer defined in stdio.h, which is used to initialize pointer type variables . Use a simple 0 instead of NULLin case you want to initialize non-pointer variables.