2 years ago
#61814
Silverlord
Why is my C code not keeping the state of static variables?
So, all information I've found online points to JNI keeping state of global variables defined on C.
However, In my particular case, this isn't working.
C Code:
//*snip* (just the includes)
static int sockfd = -2;
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
printf("Calling onLoad\n");
return JNI_VERSION_1_4;
}
JNIEXPORT jboolean JNICALL cinit
(JNIEnv * env, jobject obj){
sockfd = 5; //This would normally be the socket initialization code, but this is a lot simpler and also fails.
printf("Open %d\n",sockdf); // This prints 5.
return 1;
}
JNIEXPORT jboolean JNICALL cwrite
(JNIEnv * env, jobject obj, jbyteArray bytes){
// a is a valid array.
printf("Write %d\n",sockfd); // This prints -2!!!!
if ((b = write(sockfd, a, sizeof(a))) < 0){
perror("write");
return 0;
}
return 1;
}
The Java code just inits the library with a single loadLibrary inside a static block, and then calls open, then write in sucession.
Any idea of what am I doing wrong here? Thank you in advance!
The prints I get from those are:
Calling onLoad Open 5 Write -2
EDIT: simplified the example a bit more, and added the suggestions from the comments.
c
java-native-interface
0 Answers
Your Answer