java代码
public class DemoActivity extends Activity {
static{
System.loadLibrary("Hello");
}
public native String hello_from_c();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(this, hello_from_c(), 0).show();
}
}
使用javah工具快速生成(在JAVA代码中声明native方法的文件)生成头文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class cn_itcast_ndk2_DemoActivity */
#ifndef _Included_cn_itcast_ndk2_DemoActivity
#define _Included_cn_itcast_ndk2_DemoActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: cn_itcast_ndk2_DemoActivity
* Method: hello_from_c
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_cn_itcast_ndk2_DemoActivity_hello_1from_1c
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
c++代码
#include <stdio.h>
#include "cn_itcast_ndk2_DemoActivity.h"#include <android/log.h>
#define LOG_TAG "System.out"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
JNIEXPORT jstring JNICALL Java_cn_itcast_ndk2_DemoActivity_hello_1from_1c
(JNIEnv * env, jobject ){
LOGD("begin");
// intt a;
//定义一个字符串的常量 (不能被修改的变量)
// const char* str1 = "hello";
// LOGD("INIT STR1");
// const char* str2 = "zhang san";
// LOGD("init str2");
// LOGD("str1=%s",str1);
// LOGD("str2=%s",str2);
// c代码不允许修改一个字符串的常量
// strcat(str1,str2);
// LOGD("strcat");
char* str = "你好 ,中国";
// return (**env).NewStringUTF(env, str);
//jni.h文件对c++对一些方法做了一些包装所以不需要*这个标记了
return (env)->NewStringUTF( str);}