步骤:
1. 把c文件后缀名换成cpp
2. Android.mk文件中的hello.c也要换成hello.cpp
3. c++的使用的环境变量结构体中,访问了c使用的结构体的函数指针,函数名全部都是一样的,只是参数去掉了结构体指针
4. 访问函数指针时,把env前面的*号去掉,因为此时env已经是一级指针
5. clean,清除之前编译的残留文件
6. 把声明函数的h文件放入jni文件夹中,include该h文件
public class MainActivity extends Activity {
static{
System.loadLibrary("hello");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
Toast.makeText(this, helloC(), 0).show();
}
public native String helloC();
}
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello
LOCAL_SRC_FILES := hello.cpp
include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_ABI := armeabi x86
#include <jni.h>
#include "com_itheima_cplusplus_MainActivity.h"
JNIEXPORT jstring JNICALL Java_com_itheima_cplusplus_MainActivity_helloC
(JNIEnv * env, jobject obj){
char* cstr = "hello from c";
//return (*env)->NewStringUTF(env, cstr);
return env->NewStringUTF(cstr);
}
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_itheima_cplusplus_MainActivity */
#ifndef _Included_com_itheima_cplusplus_MainActivity
#define _Included_com_itheima_cplusplus_MainActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_itheima_cplusplus_MainActivity
* Method: helloC
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_itheima_cplusplus_MainActivity_helloC
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif