Retrieve environment variable (JNI)Tag(s): Environment JNI


For some odd reasons, the getenv() method was removed from the JDK. Rumors is that a mechanism to retrieve an environment will be back in JDK1.5 (see this HowTo). But for now, you can use -D switch to retrieve named environment variable and pass them to the JVM (see this HowTo) or use this JNI routine :
JNIEXPORT jstring JNICALL JavaHowTo_getenv
  (JNIEnv *env, jclass c, jstring jname){
    if ( jname == NULL ) { 
       return NULL ; 
    }
    const char *name =
       (*env)->GetStringUTFChars(env, jname, (jboolean *)NULL) ;
    const char *value = getenv(name) ;
    (*env)->ReleaseStringUTFChars(env, jname, name) ;
    return value ? (*env)->NewStringUTF(env, value) : NULL ;
}
NOTE : This is fine if the environment variable contains only regular 7-bit ASCII characters.

See also this HowTo.


blog comments powered by Disqus