Android studio uses C/C++ to develop apps

1. Select Native C++ in the new project and then next step

2. Customize the name and save location, select Java as the language, select the corresponding version of the SDK according to the platform where the app is installed, and then take the next step.

 3. C++ Standard can be selected by default, click Finish

 4. After loading is complete, change the project title Android to Project

 List after replacement

 

 The C/C++ code is in the cpp folder, and there are some usage examples in the MainActivity.java file.

 5. Click Run to view the running effect.

 Simple instructions for using the code:

Android studio uses C/C++ code to develop apps. It uses C/C++ code as a library. The C/C++ code library must be loaded in the MainActivity.java file.

// Used to load the 'myapplication' library on application startup.
static {
    System.loadLibrary("myapplication");
}

How to use the library:

1. C/C++ code must use functions in the specified format (if it is a C file, remove extern "C")

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

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

2. Add C/C++ files to the CMakeLists.txt file

add_library( # Sets the name of the library.
             myapplication

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             native-lib.cpp )

3. First define the usage in the MainActivity.java file:

public native String stringFromJNI();

4. Call the code in C/C++ in the onCreate function

// Example of a call to a native method
TextView tv = binding.sampleText;
tv.setText(stringFromJNI());

If you have your own new C/C++ files and .h header files, you need to add them to the CMakeLists.txt file.

# 头文件位置
include_directories(src/main/cpp/)

C/C++ files call Java

#include <jni.h>

JNIEnv* env=NULL;
jobject obj = NULL;
Java_com_example_myapplication_MainActivity_stringFromJNI(env,obj);

Guess you like

Origin blog.csdn.net/2301_77318278/article/details/131175553