上一节简单介绍了ndk的安装及demo运行,这次记录下demo的结构及作用
1 cpp目录及cmakeLists.txt
cp目录,是写c++源码的文件目录,创建demo后,会自带native-lib.cpp,这是一个c++返回字符串的示例
include
include
extern “C”
jstring
Java_com_buybal_www_ndkdemo2_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = “Hello from C++”;
return env->NewStringUTF(hello.c_str());
}
activity 调用c++的方式:
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
这里注意System.loadLibrary(“native-lib”),加载(native-lib)Library,这里是CmakeLists文件中配置好的Library名字要对应。
然后就是native调用stringFromJNI ()方法啦》,特别说明的是c++的方法名规则是 Java_包名_方法名
最后编译一下app,Make Project build一下,然后run到手机上就可以运行了。
2 cmakeLists.txt
add_library( # Sets the name of the library.
native-lib //生成so文件名
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
src/main/cpp/native-lib.cpp //生成so文件的源文件
)
描述的可能有些不详细,多拿demo改改看看效果就能摸清门道了,摸清demo后,入了门,就进入实践阶段了,敬请关注下一集。