Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 979
antoncrimea Avatar asked Jan 15 '23 21:01

antoncrimea


1 Answers

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

like image 72
William Seemann Avatar answered Jan 27 '23 23:01

William Seemann