Cmake:如何在 android studio 中包含一个 .h 文件并从 android 代码中调用头文件的方法

Cmake: How to include a .h file in android studio and call methods of header file from android code

我在 Android 中有一个 Android 应用程序 Studio.I 想用本地语言(c 或 cpp)编写我的加密逻辑。为此,我安装了 Cmake 插件。 我从 here 获得了 AES 代码。

Directory Structure of project in Android studio

CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)



add_library( # Sets the name of the library.
                         aes

                          # Sets the library as a shared library.
                          SHARED

                          src/main/cpp/aes.c )


add_library( # Sets the name of the library.
                         analyze

                          # Sets the library as a shared library.
                          SHARED

                           src/main/cpp/analyze.c )



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.
                       aes

                   # Links the target library to the log library
                   # included in the NDK.
                   ${log-lib} )

target_link_libraries( # Specifies the target library.
                        analyze

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

这是我用来引用包含的库并使用其中定义的函数的class。

analyze.c

#include <stdint.h>
#include "aes.h"

#include <jni.h>

void AES128_ECB_encrypt(const uint8_t*,const uint8_t*,uint8_t*);
JNIEXPORT jstring JNICALL
Java_cppandroid_madhu_com_cppandroid_MainActivity_invokeAESFunction(JNIEnv *env,
                                                                       jobject instance) {

    unsigned char myString [] = "This is my string";
    unsigned char mykey[]="this is key";
    //unsigned  char encryp[];

    const uint8_t *input = &myString[0];
    const uint8_t *key =&mykey[0];
    uint8_t *output;

    AES128_ECB_encrypt(input, key, output);
    return output;
} 

我面临的问题是,当我从我的 MainActivity 调用 invokeAESFunction() 时,我收到一个名为的错误:"undefined reference to AES128_ECB_encrypt()."有人请帮助我。

我假设您在 activity 中错过了 aes 库加载:System.loadLibrary("aes")

您的 CMakeLists.txt 应如下所示:

cmake_minimum_required(VERSION 3.4.1)
set(SOURCE cpp/native-lib.c  cpp/aes.c)
add_library( native-lib  SHARED ${SOURCE} )
find_library( log-lib log )
target_link_libraries( native-lib ${log-lib} )