使用C ++采用Android NDK / JNIAndroid、NDK、JNI

2023-09-05 05:54:57 作者:抱着一腔热血

所有的NDK样本仅利用声明为extern在页眉和cpp文件中定义基本的C函数。然后包括在包含JNI回调的C文件的头文件之后,一切工作正常。

All the ndk samples only make use of basic C functions declared as extern in the header and defined in the cpp file. Then after including the header file in the C file containing the jni callback, everything works fine.

是否可以使用C ++类的Andr​​oid NDK?我的应用程序不会成为一个本地的活动,它仍然有一个重要的Java的一部分,但它会调用本机C code为CPU密集型计算(已用C ++编写,使用类和其他C ++的东西)。

Is it possible to use C++ classes with the android ndk? My application is not going to be a native activity, it will still have an important java part but it will call native C code for CPU-intensive computation (already written in C++, with classes and other C++ stuff).

下面是我的hello-world状晶格结构现在:

Here is my hello-world like strcuture for now:

文件first.h

#ifndef FIRST_H
#define FIRST_H

class Test
{};

#endif /* FIRST_H */

文件second.cpp

File "second.cpp"

#include <jni.h>
#include "first.h"

#ifdef __cplusplus
extern "C" {
#endif

jint Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
                                      jobject  this,
                                      jint     x,
                                      jint     y )
{
    Test t;
    return 0;
}

#ifdef __cplusplus
}
#endif

最后Android.mk

And finally Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-second
LOCAL_SRC_FILES := second.cpp

include $(BUILD_SHARED_LIBRARY)

pretty的基本的,但无法编译。包括头文件时谈到second.cpp在.c文件提出了一个错误,我想这是因为它不是一个C ++文件。

Pretty basic but that does not compile. Turning second.cpp in a .c file raises an error when including the header file, I guess this is because it is not a C++ file.

error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Test'

制作它的.cpp引发以下错误:

Making it .cpp raises the following error:

make: *** No rule to make target `/cygdrive/c/android-ndk-r5c/samples/twolibs/jni/second.c', needed by `/cygdrive/c/android-ndk-r5c/samples/two-libs/obj/local/armeabi/objs/twolib-second/second.o'.  Stop.

任何想法如何,我可以作出这样的事情编译?

Any idea how I can make that thing compile?

感谢

推荐答案

您可以使用C ++与NDK,但文件和C ++ code必须具有.cpp扩展名。

You can use C++ with NDK, but files with C++ code must have .cpp extension.

在 Android的MK.html

请注意,默认扩展C ++源文件是拥有更高的优先权。它是   但是,可以通过定义变量来指定一个不同的   LOCAL_CPP_EXTENSION。不要忘了最初的点(即.CXX'会   的工作,而不是CXX)。

Note that the default extension for C++ source files is '.cpp'. It is however possible to specify a different one by defining the variable LOCAL_CPP_EXTENSION. Don't forget the initial dot (i.e. '.cxx' will work, but not 'cxx').