Cmake编写JNI
调用两个库
CMakeLists.txt
//把那种大段的注释去掉了 cmake_minimum_required(VERSION 3.4.1) add_library( # Sets the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). src/main/cpp/native-lib.cpp ) add_library( # Sets the name of the library. nativeSecond-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). src/main/cpp/nativeSecond-lib.cpp ) find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log ) target_link_libraries( # Specifies the target library. native-lib # Links the target library to the log library # included in the NDK. ${log-lib} ) target_link_libraries( # Specifies the target library. nativeSecond-lib # Links the target library to the log library # included in the NDK. ${log-lib} )
native-lib.cpp
#include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_com_example_aplex_cantest_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); }
nativeSecond-lib.cpp
#include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_com_example_aplex_cantest_MainActivity_stringFromJNI22( JNIEnv *env, jobject /* this */) { std::string hello = "Hello Second from C++"; return env->NewStringUTF(hello.c_str()); }
MainActivity.java
package com.example.aplex.cantest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); System.loadLibrary("nativeSecond-lib"); } Button bt; TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Example of a call to a native method tv = (TextView) findViewById(R.id.sample_text); tv.setText(stringFromJNI()); bt = (Button)findViewById(R.id.bt); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tv.setText(stringFromJNI22()); } }); } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ public native String stringFromJNI(); public native String stringFromJNI22(); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端