java为了调用底层驱动函数,需要调用外部的C/C++代码,java提供了JNI接口:
1 #include <stdio.h> 2 #include <jni.h> 3 4 jint ledOpen(JNIEnv *env, jobject cls) 5 { 6 printf("all led opened\n"); 7 return 0; 8 } 9 10 jint ledCtrl(JNIEnv *env, jobject cls, jint which, jint status) 11 { 12 printf("status of %d is %d \n", which, status); 13 return 0; 14 } 15 16 void ledClose(JNIEnv *env, jobject cls) 17 { 18 printf("all led closed\n"); 19 } 20 21 static JNINativeMethod gMethods[] ={ 22 {"ledCtrl", "(II)I", (void *)ledCtrl}, 23 {"ledOpen", "()I", (void *)ledOpen}, 24 {"ledClose", "()V", (void *)ledClose}, 25 }; 26 27 28 JNIEXPORT jint JNICALL 29 JNI_OnLoad(JavaVM *jvm, void *reserved) 30 { 31 JNIEnv *env; //struct JNINativeInterface_ * 32 33 if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_4)) { 34 return -1; 35 } 36 jclass cls = (*env)->FindClass(env, "com/example/hardlibrary/HardControl"); //java里面类的路径 37 if (cls == NULL) { 38 return -1; 39 } 40 if((*env)->RegisterNatives(env,cls, gMethods, sizeof(gMethods)/sizeof(gMethods[0]))< 0) { 41 return -1; 42 } 43 44 return JNI_VERSION_1_4; 45 }
原文:https://www.cnblogs.com/zhu-g5may/p/10453223.html