Created
November 10, 2010 03:00
-
-
Save kurohuku/670273 to your computer and use it in GitHub Desktop.
jni from c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <jni.h> | |
int main(){ | |
JNIEnv *env; | |
JavaVM *jvm; | |
int res; | |
jclass clazz; | |
jmethodID mid; | |
jmethodID mid_to_str; | |
jobject obj; | |
jstring result; | |
const char *bytes; | |
jsize len; | |
int i = 0; | |
JavaVMOption options[1]; | |
options[0].optionString = "-verbose:gc"; | |
JavaVMInitArgs vm_args; | |
vm_args.version = JNI_VERSION_1_4; | |
vm_args.options = options; | |
vm_args.nOptions = 1; | |
res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args); | |
if(res < 0){ | |
printf("Error on JNI_CreateJavaVM\n"); | |
return -1; | |
} | |
clazz = (*env)->FindClass(env, "Ljava/util/Date;"); | |
if(clazz == 0){ | |
printf("error on FindClass\n"); | |
return -1; | |
} | |
// コンストラクタは"<init>"で取得 | |
mid = (*env)->GetMethodID(env,clazz, "<init>","()V"); | |
if(mid == NULL){ | |
printf("error on GetMethodId(<init>);\n"); | |
return -1; | |
} | |
obj = (*env)->NewObject(env,clazz, mid); | |
if(obj == NULL){ | |
printf("error on NewObject\n"); | |
return -1; | |
} | |
mid_to_str = (*env)->GetMethodID(env,clazz, "toString", "()Ljava/lang/String;"); | |
if(mid_to_str == NULL){ | |
printf("error on GetMethodID(toString)\n"); | |
return -1; | |
} | |
result = (jstring)(*env)->CallNonvirtualObjectMethod(env,obj, clazz, mid_to_str); | |
if(result == NULL){ | |
printf("error on CallNonvirtualObjectMethod\n"); | |
return -1; | |
} | |
bytes = (*env)->GetStringUTFChars(env,result,NULL); | |
printf("bytes = %p\n", bytes); | |
len = (*env)->GetStringLength(env,result); | |
printf("len = %d\n", len); | |
for(i = 0; i < len; i++){ | |
printf("%d,", bytes[i]); | |
} | |
printf("\n"); | |
(*env)->ReleaseStringUTFChars(env,result, bytes); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gcc -lverify -ljava -ljvm test.c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment