JNI的注意

xiaoxiao2025-04-15  20

jni方式分两种

1、JNIEXPORT jint JNICALL java调用loadLibrary处包名加方法名 2、JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)中指定包名
第二种方法需要注意在头文件中进行定义

方法一示例:

jni代码
// jni实现 JNIEXPORT static jint Native_API_Led_turnOn(JNIEnv * env, jobject obj,jint paramInt){ return 0; } //映射关系 static JNINativeMethod getMethods[] = { {"ApiLedTurnOn","(I)I",(void*)Native_API_Led_turnOn}, }; static int registerNatives(JNIEnv* env){ //指定类的路径,通过FindClass 方法来找到对应的类 const char* className = "com/lhxx/jni/server/PrivateAPIWrapper"; return registerNativeMethods(env,className,getMethods, sizeof(getMethods)/ sizeof(getMethods[0])); } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved){ JNIEnv* env = NULL; //判断虚拟机状态是否有问题 if((*vm)->GetEnv(vm,(void**)&env,JNI_VERSION_1_4)!= JNI_OK){ return -1; } assert(env != NULL); //开始注册函数 registerNatives -》registerNativeMethods -》env->RegisterNatives if(!registerNatives(env)){ return -1; } //返回jni 的版本 return JNI_VERSION_1_4; }
java代码
package com.lhxx.jni.server; public class PrivateAPIWrapper { public PrivateAPIWrapper(){ } static{ System.loadLibrary("jni_lhxx_server"); } public static native int ApiLedTurnOn(int paramInt); }
Android.mk
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE_TAGS := optional LOCAL_MODULE := libjni_test LOCAL_LDLIBS += -llog -ldl LOCAL_SHARED_LIBRARIES := libutils LOCAL_SRC_FILES := \ jni_lhxx_server.c LOCAL_C_INCLUDES += \ $(JNI_H_INCLUDE) include $(BUILD_SHARED_LIBRARY)

方法二示例:

java代码
public class JNIExtPrinter { static { System.loadLibrary("config_ext_printer"); } public native int nativeConfig4gethernet(int onOff); // 0:off others:on public JNIExtPrinter() { // TODO Auto-generated constructor stub }

}

jni代码
config_extprinter.c文件
#include "config_extprinter.h" #include <stdlib.h> #include <errno.h> #include <sys/ioctl.h> #include <fcntl.h> #include <utils/Log.h> #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) JNIEXPORT jint JNICALL Java_com_android_settings_JNIExtPrinter_nativeConfig4gethernet{ return 0; }
config_extprinter.h文件
#ifdef __cplusplus extern "C" { #endif /* * Class: Java_com_android_settings_JNIExtPrinter * Method: nativeConfigExtPrinter * Signature: (I)I */ JNIEXPORT jint JNICALL Java_com_android_settings_JNIExtPrinter_nativeConfig4gethernet (JNIEnv *, jobject, jint); #ifdef __cplusplus } #endif #endif
Android.mk
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE_TAGS := optional LOCAL_MODULE := libconfig_ext_printer LOCAL_LDLIBS += -llog LOCAL_SHARED_LIBRARIES := libutils LOCAL_SRC_FILES := \ config_extprinter.cpp LOCAL_C_INCLUDES += \ $(JNI_H_INCLUDE) \ include $(BUILD_SHARED_LIBRARY)
转载请注明原文地址: https://www.6miu.com/read-5028303.html

最新回复(0)