简体   繁体   中英

How compile c++ project via Android NDK

I have small C++ library project with one class.

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

I can build this class via Android NDK. (Question 1). I can use .so file into Java application. How I can call SomeFunc method from Java code (Question 2).

Here are the steps:

1.) Create Android.mk in the project's "jni" folder:

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:

#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):

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

4.) Define the native function in the calling activity:

native int SomeFunc();

5.) Call it from the activity:

@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)

7.) Re-build and run the application

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.

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(); 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. .so will help your java class know ,what your c code wants to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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