简体   繁体   English

如何通过Android NDK编译c ++项目

[英]How compile c++ project via Android NDK

I have small C++ library project with one class. 我有一个小类的C ++库项目。

class Test
{
public:
Test(){};
~Test(){};
int SomeFunc() { return 5; }
}

I can build this class via Android NDK. 我可以通过Android NDK构建这个类。 (Question 1). (问题1)。 I can use .so file into Java application. 我可以将.so文件用于Java应用程序。 How I can call SomeFunc method from Java code (Question 2). 我如何从Java代码调用SomeFunc方法(问题2)。

Here are the steps: 以下是步骤:

1.) Create Android.mk in the project's "jni" folder: 1.)在项目的“jni”文件夹中创建Android.mk:

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := main_jni
LOCAL_CFLAGS := 
LOCAL_SRC_FILES := main.cpp
LOCAL_LDLIBS :=

include $(BUILD_SHARED_LIBRARY)

2.) Create main.cpp in the "jni" folder: 2.)在“jni”文件夹中创建main.cpp:

#include <jni.h>
using namespace std;

#ifdef __cplusplus
extern "C" {
#endif

class Test {
public:
Test(){};
~Test(){};
int SomeFunc() { return 5; }
};

jint Java_com_example_activity_MainActivity_SomeFunc(JNIEnv *env, jobject thiz)
{
    Test *test = new Test();
    return test->SomeFunc();
}

#ifdef __cplusplus
}
#endif

3.) Add a call to load the library in your calling activity (MainActivity.java in this example): 3.)添加一个调用来加载调用活动中的库(本例中为MainActivity.java):

static {
    System.loadLibrary("main_jni");
}

4.) Define the native function in the calling activity: 4.)在调用活动中定义本机函数:

native int SomeFunc();

5.) Call it from the activity: 5.)从活动中调用它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView text = (TextView) this.findViewById(R.id.text);

    text.setText(String.valueOf(SomeFunc()));
}

6.) Run the "ndk-build" command from the project's root folder (Note: refresh the project in Eclipse after this step) 6.)从项目的根文件夹运行“ndk-build”命令(注意:在此步骤之后刷新Eclipse中的项目)

7.) Re-build and run the application 7.)重新构建并运行应用程序

I'm not sure I understand the questions correctly but this link could be useful to you. 我不确定我是否正确理解了这些问题,但这个链接可能对您有用。 I'm personally do not know much of C except for the very basics, but I look forward to getting to more C with the NDK. 我个人对C的了解不多,除了基础知识,但我期待着用NDK获得更多的C语言。

Whatever code you write in c you need to define it like java_urpackagename_class_methodname then before using this code u need to first create a native method in java class like public native int ABC(); 无论你在c中编写什么代码,你都需要像java_urpackagename_class_methodname一样定义它,然后在使用这段代码之前你需要先在java类中创建一个本机方法,如public native int ABC(); telling it that you are going to use this method.To use it do create an Android.mk or Application.mk as per your need. 告诉它您将使用此方法。要使用它,请根据需要创建Android.mk或Application.mk。 .so will help your java class know ,what your c code wants to do. .so将帮助您的java类知道您的c代码想要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM