JNI_Android项目中调用.so动态库实现详解
转自:http://www.yxkfw.com/?p=7223
1. 在Eclipse中创建项目:TestJNI
2. 新创建一个class:TestJNI.java
package com.wwj.jni; public class TestJNI { public native boolean Init(); public native int Add(int x, int y); public native void Destory(); }
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_wwj_jni_TestJNI */ #ifndef _Included_com_wwj_jni_TestJNI #define _Included_com_wwj_jni_TestJNI #ifdef __cplusplus extern "C" { #endif /* * Class: com_wwj_jni_TestJNI * Method: Init * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_com_wwj_jni_TestJNI_Init (JNIEnv *, jobject); /* * Class: com_wwj_jni_TestJNI * Method: Add * Signature: (II)I */ JNIEXPORT jint JNICALL Java_com_wwj_jni_TestJNI_Add (JNIEnv *, jobject, jint, jint); /* * Class: com_wwj_jni_TestJNI * Method: Destory * Signature: ()V */ JNIEXPORT void JNICALL Java_com_wwj_jni_TestJNI_Destory (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
#ifndef _TEST_JNI_ADD_H_ #define _TEST_JNI_ADD_H_ class CAdd { public: CAdd(); ~CAdd(); int Add(int x, int y); }; #endif
Add.cpp
#include "Add.h" CAdd::CAdd() { } CAdd::~CAdd() { } int CAdd::Add(int x, int y) { return x + y; }
com_wwj_jni_TestJNI.cpp的实现:
#include <stdio.h> #include <stdlib.h> #include "com_wwj_jni_TestJNI.h" #include "Add.h" CAdd *pCAdd = NULL; JNIEXPORT jboolean JNICALL Java_com_wwj_jni_TestJNI_Init(JNIEnv *env, jobject obj) { if (pCAdd == NULL) { pCAdd = new CAdd; } return pCAdd != NULL; } JNIEXPORT jint JNICALL Java_com_wwj_jni_TestJNI_Add(JNIEnv *env, jobject obj, jint x, jint y) { int res = -1; if (pCAdd != NULL) { res = pCAdd->Add(x, y); } return res; } JNIEXPORT void JNICALL Java_com_wwj_jni_TestJNI_Destory(JNIEnv *env, jobject obj) { if (pCAdd != NULL) { pCAdd = NULL; } }
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := TestJNI LOCAL_SRC_FILES := com_wwj_jni_TestJNI.cpp LOCAL_SRC_FILES += Add.cpp include $(BUILD_SHARED_LIBRARY)
APP_PROJECT_PATH := $(call my-dir)
APP_MODULES := TestJNI
package com.wwj.jni; import android.os.Bundle; import android.widget.TextView; import android.app.Activity; public class TestJNIActivity extends Activity { private TextView textView; static { // 加载动态库 System.loadLibrary("TestJNI"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textview); TestJNI testJNI = new TestJNI(); // 调用native方法 boolean init = testJNI.Init(); if (init == true) { // 调用Add函数 int sum = testJNI.Add(100, 150); textView.setText("你真是个" + sum); } else { textView.setText("你比二百五还要二百五"); } testJNI.Destory(); } }
运行项目,效果图如下:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。