2013年(13)
分类: Android平台
2013-05-22 16:46:46
jni的编写
java调用c/c++的框架
java代码-->jni代码--->c/c++代码
写一个简单的java app来调用c/c++代码打印“HelloWorld!”的过程。分为3步:
1、编写java代码,创建一个类(HelloWorld.java)声明native method
2、编写jni文件。
3、将jni实现文件编译成一个native lib
HelloWorld.java
public class HelloActivity extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.fsSayHello();
}
static {
System.loadLibrary("hello_jni");
}
private static native int fsSayHello();
}
构建jni函数,并且编译成本地库
jint JNI_OnLoad(JavaVM* vm, void* reserved){
jint result = -1;
JNIEnv* env = NULL;
LOGI("JNI_OnLoad");
if(vm->GetEnv( (void **)&env, JNI_VERSION_1_4) != JNI_OK){
LOGE("ERROR: GetEnv failed");
return result;
}
if (registerNatives(env) != JNI_TRUE){
LOGE("ERROR:registerNatives failed");
reture result;
}
result = JNI_VERSION_1_4;
}
static JNINativeMethod gMethods[] = {
{"fsSayHello" , "()I" , (void *)hello_printf},
};
//声明fsSayHello()所在类
static const char *classPathName = "com/farsight/HelloActivity";
static int registerNatives(JNIEnv* env){
jclass clazz;
clazz = env->FindClass(class PathName);
if (clazz == NULL){
return JNI_FALSE;
}
//向VM(即AndroidRuntime)登记gMethods[]表格所含的本地函数
if (env->RegisterNatives(clazz, gMethods, sizeof(gMethods)/sizeof(gMethods[0])) < 0){
return JNI_FALSE;
}
return JNI_TRUE;
}
typedef struct{
const char* name;
const char* signature;
void* fnPtr;
}JNINativeMethod;
编写c/c++代码
static jint hello_printf(JNIEnv* env, jobject thiz){
LOGI("<<<<<<
return 0;
}
Android.mk
LOCAL_PATH:=$(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES:= \
com.farsight.hello.cpp
LOCAL_SHARED_LIBRARIES:= \
libutils
LOCAL_C_INCLUDES+= \
$(JNI_H_INCLUDE)
LOCAL_MODULE:= libhello_jni
LOCAL_PRELILNK_MODULE:= false
include $(BUILD_SHARED_LILBRARY)