jni demo 求和

TestActivity.
package edu.usc.nsl.carma;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import edu.usc.nsl.carma.nativecaller.NativeCaller;

public class TestActivity extends ActionBarActivity {

	private NativeCaller nc;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);
		
		//final TextView textview = (TextView) findViewById(R.id.textview1);
		
		nc = new NativeCaller();
		
		final Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	nc.call1();
            }
        });
        
        final Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	nc.call2();
            }
        });
        
        final Button button3 = (Button) findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	nc.call3();
            }
        });
	}

}

NativeCaller


package edu.usc.nsl.carma.nativecaller;

import android.util.Log;

/**
 * The NDK seems fairly restrictive in terms of what java classes may make a call
 * to the native functions since these functions must contain in their name, 
 * the name fo the java classes that are allowed to call them
 * 
 * This Native Caller is a central interface to all of the native functions written
 * for this application, as in all native function declarations contain "NativeCaller"
 * in their name.
 */
public class NativeCaller {

	private static final String DEBUG_TAG = "JAVA";
	
	// Don't make these static
	private native void helloLog(String logThis);
	private native String getString(int value1, int value2);
	private native String stringFromJNI();
	
	// The name (ndk1) of the native library is defined in the makefile
	static {
		System.loadLibrary("ndk1");
	}
	
	public NativeCaller() {
		super();
	}
	
	//c example accepting a string and making a call to the Android log util
	public void call1() {
		helloLog("This will log to LogCat via the native call.");
	}
	
	//c example doing some math and returning a string
	public void call2() {
		String result = getString(5,2);
		Log.v(DEBUG_TAG, "Result: "+result); 
		result = getString(105, 1232);
		Log.v(DEBUG_TAG, "Result2: "+result);
	}
	
	//c++ example returning a string
	public void call3() {
		Log.v(DEBUG_TAG, stringFromJNI());
	}

}



Android.mk


LOCAL_PATH := $(call my-dir)


include $(CLEAR_VARS)


LOCAL_LDLIBS := -llog


# Discussion on compiling multiple source files:
# https://groups.google.com/forum/#!topic/android-ndk/R8q-5bFc3SA
LOCAL_MODULE    := ndk1
LOCAL_SRC_FILES := native.c hello-jni.cpp


include $(BUILD_SHARED_LIBRARY)



hello-jni.cpp


#include <string.h>
#include <jni.h>

/**
 * Taken from here:
 * http://taylorpeer.com/hello-world-cpp-android-ndk/
 */

extern "C" {

	/**
	 * c++ example returning a string
	 *
	 * JNIEXPORT jstring JNICALL would be a more explicit way of defining the return data type,
	 * though this appears to not be neccessary
	 */
	jstring Java_edu_usc_nsl_carma_nativecaller_NativeCaller_stringFromJNI (JNIEnv *env, jobject obj) {
		return env->NewStringUTF("Hello from C++ over JNI!");
	}

}


native.c


#include <jni.h>
#include <stdio.h>
#include <string.h>
#include <android/log.h>

#define DEBUG_TAG "NDK"

/**
 * Taken from here:
 * http://code.tutsplus.com/tutorials/advanced-android-getting-started-with-the-ndk--mobile-2152
 */

/**
 * Naming convention for functions writen for the NDK:
 * T Java__package-name_class-name_method-name(){}
 */

//c example accepting a string and making a call to the Android log util
void Java_edu_usc_nsl_carma_nativecaller_NativeCaller_helloLog(JNIEnv * env,
		jobject this, jstring logThis) {
	jboolean isCopy;
	const char * szLogThis = (*env)->GetStringUTFChars(env, logThis, &isCopy);

	__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK:LC: [%s]",
			szLogThis);

	(*env)->ReleaseStringUTFChars(env, logThis, szLogThis);
}

//c example doing some math and returning a string
jstring Java_edu_usc_nsl_carma_nativecaller_NativeCaller_getString(
		JNIEnv * env, jobject this, jint value1, jint value2) {

	char *szFormat = "The sum of the two numbers is: %i";
	char *szResult;

	// add the two values
	jlong sum = value1 + value2;

	// malloc room for the resulting string
	szResult = malloc(sizeof(szFormat) + 20);

	// standard sprintf
	sprintf(szResult, szFormat, sum);

	// get an object string
	jstring result = (*env)->NewStringUTF(env, szResult);

	// cleanup
	free(szResult);

	return result;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当您在Java程序中需要调用C/C++代码时,可以使用Java Native Interface(JNI)来实现。下面是一个简单的JNI示例,演示了如何将Java方法与C函数相互调用: 1. 创建一个Java类,例如"JNIDemo.java",其中包含您想要调用的本地方法: ```java public class JNIDemo { // 本地方法声明 public native void sayHello(); // 加载本地库 static { System.loadLibrary("jni_demo"); // 加载名为"jni_demo"的本地库 } // 测试 public static void main(String[] args) { JNIDemo demo = new JNIDemo(); demo.sayHello(); // 调用本地方法 } } ``` 2. 在命令行中使用`javac`编译Java类:`javac JNIDemo.java`。 3. 生成C头文件,可以使用`javah`工具:`javah JNIDemo`。这将生成名为"JNIDemo.h"的头文件。 4. 创建一个C源文件,例如"jni_demo.c",实现您在Java中声明的本地方法: ```c #include <stdio.h> #include "JNIDemo.h" JNIEXPORT void JNICALL Java_JNIDemo_sayHello(JNIEnv *env, jobject obj) { printf("Hello from C!\n"); } ``` 5. 在命令行中使用C编译器编译C源文件,并生成共享库文件(DLL或SO): - 对于Windows(使用MinGW):`gcc -shared -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" jni_demo.c -o jni_demo.dll` - 对于Linux/Mac:`gcc -shared -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" jni_demo.c -o libjni_demo.so` 注意:请将`$JAVA_HOME`替换为您Java安装的实际路径。 6. 运行Java程序:`java JNIDemo`。您将看到输出:"Hello from C!"。 这是一个简单的JNI示例,演示了如何在Java和C之间进行方法调用。您可以根据自己的需求扩展和定制此示例。希望对您有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值